题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
        // write code here
        vector<vector<int>> res;
        queue<TreeNode*> q;
        if (root) q.push(root);
        while(q.size()) {
            vector<int> level;  // 一层
            int len = q.size();

            // 层序遍历
            while(len -- ) {
                auto t = q.front();  // 取队首元素
                q.pop();  // 删除队首元素
                level.push_back(t->val);  // 保存当前层的值
                if (t->left) q.push(t->left);  // 如果左边还有就存入队列
                if (t->right) q.push(t->right);  // 如果右边还有就存入队列
            }
            res.push_back(level);  // 答案存下 一层
        }
        return res;
    }
};
#求二叉树的层序遍历#
全部评论

相关推荐

李橙子:结果虽不够理想,但过程本身已是宝贵的淬炼。能把学习机会放在薪酬之前,证明你目光长远。先踏实进去,用这段时间扎实学好Python后端,把公司项目吃透,你的价值会在下一份工作中完全体现。这个起点,值得。
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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