题目
题解
-
如何记录结点的层数?
二叉树的层序遍历用队列实现,是刻在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 -
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;
}
}