从上往下打印二叉树

你快乐吗?

Posted by bbkgl on September 26, 2019

从上往下打印二叉树

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) {
        queue<TreeNode*> q;
        vector<int> ans;
        if (!root) return ans;
        q.push(root);
        while (!q.empty()) {
            TreeNode* now = q.front();
            q.pop();
            ans.push_back(now->val);
            if (now->left)
                q.push(now->left);
            if (now->right)
                q.push(now->right);
        }
        return ans;
    }
};