从上到下打印二叉树

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

【思路】此题目实为层次遍历,二叉树的遍历除了层次遍历外,还有先序,中序,后序遍历,之前的文章中讲的很详细了!层次遍历需要队列来进行数据的储存!!!并且层次遍历的迭代版非常容易实现,自行看代码吧。

/*
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> res;

         if(!root)
            return res;      //如果为空,则需要返回空vector
        queue<TreeNode *> tmp;
        tmp.push(root);

        while(!tmp.empty()){
            TreeNode* node = tmp.front();
            res.push_back(node->val);    //取出队头数据
            tmp.pop();
            if(node->left)
                tmp.push(node->left);
            if(node->right)
                tmp.push(node->right);
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/zhudingtop/p/11333919.html