LintCode 二叉树的层次遍历

该博客介绍了一种二叉树层次遍历的方法,通过广度优先搜索(BFS)策略逐层从左到右访问节点。具体以样例二叉树为例,展示了层次遍历的结果,并提供了相应的AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

您在真实的面试中是否遇到过这个题? Yes
样例
给一棵二叉树 {3,9,20,#,#,15,7} :

3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:

[
[3],
[9,20],
[15,7]
]

思路分析:

bfs遍历。

ac代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
public:
    vector<vector<int>> v;
    void bfs(TreeNode *root)
    {
        int len=1,i,j,k;
        TreeNode *temp;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            vector<int> num;
            k=0;
            for(i=0;i<len;i++)
            {
                temp=q.front();
                q.pop();
                num.push_back(temp->val);
                if(temp->left!=NULL)
                {
                    k++;
                    q.push(temp->left);
                }
                if(temp->right!=NULL)
                {
                    k++;
                    q.push(temp->right);
                }
            }
            len=k;
            v.push_back(num);
        }
    }
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here
        if(!root)
            return v;
        bfs(root);
        return v;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值