剑指offer 把二叉树打印成多行

题目描述

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

代码:层次遍历,简单

class Solution {
public:
        vector<vector<int> > Print(TreeNode* root) {
            vector<vector<int> >ans;
            if(root==NULL)return ans;
            queue<TreeNode*>q;
            q.push(root);
            while(!q.empty()){
                queue<TreeNode*>qt;
                vector<int>res;
                while(!q.empty()){
                    TreeNode*t=q.front();q.pop();
                    res.push_back(t->val);
                    if(t->left)qt.push(t->left);
                    if(t->right)qt.push(t->right);
                }
                ans.push_back(res);
                q=qt;
            }
            return ans;
        }
};

猜你喜欢

转载自blog.csdn.net/weixin_42130471/article/details/80710296