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

把二叉树打印成多行

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

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int>> res;
    // 层序遍历
    vector<vector<int> > Print(TreeNode* pRoot) {
        // write code here
        if(!pRoot) return res;
        queue<TreeNode*> q;
        q.push(pRoot);
        vector<int> v;
        while (!q.empty()) {
            int num = q.size();
            for(int i = 0; i < num; ++i)
            {
                TreeNode* tmp = q.front();
                q.pop();
                v.push_back(tmp->val);
                if(tmp->left) q.push(tmp->left);
                if(tmp->right) q.push(tmp->right);
            }
            res.push_back(v);
            v.clear();
        }
        return res;
    }
};

挤挤刷刷! 文章被收录于专栏

记录coding过程

全部评论

相关推荐

今天 03:40
已编辑
电子科技大学 Java
在秋招的小白菜很想养修勾:一眼 苍穹外卖+谷粒商城,项目换一换吧,可以找一些付费知识星球博主带带,避免烂大街。多投投大厂,背背八股,你这学历乱杀了,等实习经验到位,到时候大厂闭眼选
投递美团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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