牛客刷题之二叉树的层序遍历

题目描述

给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},

该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]

示例1
输入

{1,2}

输出

[[1],[2]]

示例2
输入

{1,2,3,4,#,#,5}

输出

[[1],[2,3],[4,5]]

牛客链接:

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3?tpId=188&&tqId=35315&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

解题思路:
首先层次遍历使用队列
用node.size()来获取当前层数据的数据量
然后用cur来记录当前层的数据,每遍历完一层,将cur中的数据直接push_back到num中

代码:

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
        // write code here
        vector<vector<int>> num;
        if (root == NULL) {
            return num;
        }
        queue<TreeNode*> node;
        node.push(root);
        vector<int> cur;
        while(!node.empty()) {
            cur.clear();
            int n = node.size();
            for(int i=0; i<n; i++) {
                 TreeNode* temp = node.front();
                if(temp->left != NULL) {
                    node.push(temp->left);
                }
                if(temp->right != NULL) {
                    node.push(temp->right);
                }
                node.pop();
                cur.push_back(temp->val);
            }
            num.push_back(cur);
        }
        return num;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值