Skip to content

Commit 35018d7

Browse files
authored
102. 二叉树的层次遍历打卡
1 parent 1bcf6b2 commit 35018d7

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
[102. 二叉树的层次遍历] (https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)
2+
3+
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
4+
5+
例如:
6+
给定二叉树: [3,9,20,null,null,15,7],
7+
8+
3
9+
/ \
10+
9 20
11+
/ \
12+
15 7
13+
返回其层次遍历结果:
14+
15+
[
16+
[3],
17+
[9,20],
18+
[15,7]
19+
]
20+
21+
22+
```
23+
/**
24+
* Definition for a binary tree node.
25+
* public class TreeNode {
26+
* int val;
27+
* TreeNode left;
28+
* TreeNode right;
29+
* TreeNode(int x) { val = x; }
30+
* }
31+
*/
32+
// TODO 解题关键:传递树高度
33+
class Solution {
34+
public List<List<Integer>> levelOrder(TreeNode root) {
35+
List<List<Integer>> result = new ArrayList<>();
36+
if(root == null) return result;
37+
executor(root,result,0);
38+
return result;
39+
}
40+
41+
public void executor(TreeNode node,List<List<Integer>> result,int high){
42+
if(node == null) return;
43+
if(result.size() < high+1) result.add(new ArrayList<>());
44+
result.get(high).add(node.val);
45+
high++;
46+
executor(node.left,result,high);
47+
executor(node.right,result,high);
48+
}
49+
}
50+
```

0 commit comments

Comments
 (0)