从上往下打印二叉树

题目描述

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

代码

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

posted on 2017-03-13 09:11  jec  阅读(147)  评论(0编辑  收藏  举报

导航