【两次过】Lintcode 69:二叉树的层次遍历

本文介绍了一种通过队列实现的二叉树层次遍历算法,并提供了详细的代码实现。该算法能有效地按层次顺序输出二叉树的节点值。

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

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

样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3
 / \
9  20
  /  \
 15   7

返回他的分层遍历结果:

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

挑战

挑战1:只使用一个队列去实现它

挑战2:用DFS算法来做

解题思路:

    利用一个队列来辅助层级遍历,先将root offer进队列,再poll出来,将当前poll出的元素存进list中,考察当前队列front元素是否有左右孩子,若有则将其左右孩子offer进队列中,循环操作,直到队列为空,则表明所有元素都按照层级关系存进list中。

    注意本题需要的结果是保存在一个二维数组中,每一个层级的数据占据一行,所以单独对层级加一个一维数组temp暂存,再将temp存进res二维数组中。

注意queue是由LinkedList实现的,添加使用offer(),删除使用poll(),返回队首的元素peek().

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

public class Solution {
    /**
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        // write your code here
        if(root == null)
            return null;
        
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while(!queue.isEmpty()){
            int len = queue.size();
            ArrayList<Integer> temp = new ArrayList<>();
            
            for(int i=0 ; i<len ; i++){
                TreeNode node = queue.poll();
                temp.add(node.val);
            
                if(node.left != null)
                    queue.offer(node.left);
                
                if(node.right != null)
                    queue.offer(node.right);
            }
            
            res.add(temp);
        }
        
        return res;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值