题解 | #把二叉树打印成多行#

把二叉树打印成多行

http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

/*
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) {
            if(pRoot == nullptr){
                return {};
            }
            
            vector<vector<int>> res;
            
            queue<TreeNode*> Q;
            Q.push(pRoot);
            
            while(!Q.empty()){
                int cur_size = Q.size();
                vector<int> cur_res;
                for(int i=0; i<cur_size; i++){
                    auto node = Q.front();
                    Q.pop();
                    cur_res.push_back(node->val);
                    if(node->left){
                        Q.push(node->left);
                    }
                    if(node->right){
                        Q.push(node->right);
                    }
                }
                res.push_back(cur_res);
            }
            return res;
        }
    
};
全部评论

相关推荐

01-08 12:01
门头沟学院 Java
冰炸橙汁_不做oj版:不接好运
点赞 评论 收藏
分享
01-27 22:50
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务