guanpengchn / guanpengchn.github.io

:memo: code on DEV branch, blogs on ISSUES
https://guanpengchn.github.io
18 stars 9 forks source link

把二叉树打印成多行 #51

Open guanpengchn opened 5 years ago

guanpengchn commented 5 years ago

题目描述

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

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

};
ghost commented 4 years ago

用issues写博客---真的好鸡贼啊23333!!!!