剑指offer 从上往下打印二叉树 C++ (层序历遍)

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解答

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        vector<int> result;
        if(NULL == root)
            return result;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            TreeNode* temp=q.front();
            result.push_back(temp->val);
            if(temp->left)
            {
                q.push(temp->left);
            }
            if(temp->right)
            {
                q.push(temp->right);
            }
            q.pop();
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/yuanliang861/article/details/87900247