【剑指offer】把二叉树打印成多行(二叉树)

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

思路

与二叉树的层序遍历相同,区别在于需要逐层打印;所以需要加入两个参数来控制:toBePrinted表示当前层还没打印的节点数,nextLevel表示下一层需要打印的节点数。

当每一层打印完时(toBePrinted==0),将当前层打印的序列存下来,并更新需要打印的节点数为下一层需要打印的节点数更新 toBePrinted=nextLevel

代码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > ret;
        vector<int> tmp;

        if(pRoot == nullptr)
            return ret;

        int toBePrinted = 1;    // 当前层还没打印节点数
        int nextLevel = 0;      // 下一层需要打印节点数
        queue<TreeNode *> q;
        q.push(pRoot);
        while (!q.empty()){
            TreeNode *node = q.front();

            if (node->left != nullptr){
                nextLevel++;
                q.push(node->left);
            }

            if(node->right != nullptr){
                nextLevel++;
                q.push(node->right);
            }

            tmp.push_back(node->val);
            q.pop();
            toBePrinted --;
            if (toBePrinted == 0){
                ret.push_back(tmp);
                tmp.clear();                // 重置当前层打印记录
                toBePrinted = nextLevel;
                nextLevel = 0;
            }
        }

        return ret;
    }

};

猜你喜欢

转载自blog.csdn.net/zjwreal/article/details/89284016