分行从上到下打印二叉树

题目

  从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。例如输入下图中的二叉树,则依次打印出8、6、10、5、7、9、11

思路

  与从上到下打印二叉树类似https://www.cnblogs.com/tianzeng/p/10186431.html,本题在定义两个变量,next_level表示下一层要打印的节点数 ,在遍历的如果有字结点,就执行next_level加一操作,be_printed表示本层剩余要打印的节点数,如果为0,表示已经打印完,可以打印下一层。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        if (root == nullptr) {
            return {};
        }

        vector<int> res;
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode *cur = q.front();
            q.pop();
            res.push_back(cur->val);
            if (cur->left != nullptr) {
                q.push(cur->left);
            }
            if (cur->right != nullptr) {
                q.push(cur->right);
            }
        }
        return res;
    }
};

 

posted on 2018-12-27 21:57  tianzeng  阅读(184)  评论(0)    收藏  举报

导航