leetcode102.二叉树的层次遍历

leetcode102.二叉树的层次遍历

二月 23, 2020

leetcode 102. 二叉树的层次遍历


给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/  \
9 20
   /    \
  15   7

返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]

想法和思路来源于leetcode104二叉树的最大深度。记录下每一层有几个节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null)return new ArrayList<>();
Queue<TreeNode>queue=new LinkedList<>();
List<List<Integer>>res=new LinkedList<>();
List<Integer>list=new LinkedList<>();
int nowCount=1,inCount=0;
queue.add(root);
while(!queue.isEmpty()){
TreeNode node=queue.poll();
list.add(node.val);
nowCount--;
if(node.left!=null){
queue.add(node.left);
inCount++;
}
if(node.right!=null){
queue.add(node.right);
inCount++;
}
if(nowCount==0){
nowCount=inCount;
inCount=0;
//System.out.println(list);
res.add(list);
list=new LinkedList<>();
}
}
return res;
}

leetcode 28/100