欢迎找我内推微软

[剑指offer] 从上往下打印二叉树

题目描述

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

 

使用队列来存储操作节点。

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

 

posted @ 2017-11-28 11:36  zmj97  阅读(134)  评论(0编辑  收藏  举报
欢迎找我内推微软