【LeetCode】Day14-二叉树的层序遍历

题目

102. 二叉树的层序遍历【中等】

题解

  1. 如何记录结点的层数?

    二叉树的层序遍历用队列实现,是刻在DNA里的解法,那么问题是如何实现每层一个List,那么如何划分开每层和每层的结点呢?
    在这里插入图片描述
    方法一:(node,level)二元组记录每个结点的层,level(child)=level(parent)+1,但需要哈希表记录,之后再遍历哈希表组成答案返回,增加空间复杂度
    方法二:当前一层结点均出队以后,用 s k s_k sk记录当前队列中结点的个数,这 s k s_k sk个结点就是k层的, s k s_k sk个结点出队之后其余结点一定是他们的孩子,即下一层的结点,数目为 s k + 1 s_{k+1} sk+1

  2. Java如何实现队列?
    这是第二个问题,C++中直接用queue就行了,但是Java不行!
    在Java里Queue是继承Collection的一个抽象类,不可以实例化,需要Queue<Integer>queue=new LinkedList<Integer>();LinkedList将其实例化

Java API的官方文档里这样描述Queue的方法:

A collection designed for holding elements prior to processing.
Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false,depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.
在这里插入图片描述

此外,List也不可以实例化,需要用ArrayList将其实例化

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode>queue=new LinkedList<TreeNode>();//遍历结点的队列
        List<List<Integer>>levelorder=new ArrayList<List<Integer>>();//存层次遍历结果
        if(root==null)
            return levelorder;
        queue.offer(root);
        int sk=0;//用于记录第k层的结点数
        while(!queue.isEmpty()){
            sk=queue.size();
            List<Integer>level=new ArrayList<Integer>();//存一层的遍历结果
            while(sk>0){
                TreeNode p=queue.poll();
                level.add(p.val);
                if(p.left!=null)
                    queue.offer(p.left);
                if(p.right!=null)
                    queue.offer(p.right);
                sk--;
            }
            levelorder.add(level);//sk个结点遍历完,其余结点一定是他们的孩子,即下一层结点
        }
        return levelorder;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值