牛客网剑指offer-把二叉树打印成多行

题目描述

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


/*
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> > ans;
            if (pRoot == nullptr)
                return ans;
             queue<TreeNode*> q;
            q.push(pRoot);
            while (!q.empty())
            {
                int len = q.size();
                vector<int> vec;
                while (len--)
                {
                    vec.push_back(q.front()->val);
                    if (q.front()->left != nullptr)
                        q.push(q.front()->left);
                    if (q.front()->right != nullptr)
                        q.push(q.front()->right);
                    q.pop();
                }
                ans.push_back(vec);
            }
            return ans;
        }
    
};

猜你喜欢

转载自blog.csdn.net/yhn19951008/article/details/79434199