Skip to content

Commit f674faa

Browse files
authored
Merge pull request gzc426#14 from V1ncentzzZ/V1ncentzzZ-patch-11
103. 二叉树的锯齿形层次遍历打卡
2 parents 0509a99 + a06d2d2 commit f674faa

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
[103. 二叉树的锯齿形层次遍历](https://leetcode-cn.com/problems/binary-tree-zigzag-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+
[20,9],
18+
[15,7]
19+
]
20+
21+
```
22+
/**
23+
* Definition for a binary tree node.
24+
* public class TreeNode {
25+
* int val;
26+
* TreeNode left;
27+
* TreeNode right;
28+
* TreeNode(int x) { val = x; }
29+
* }
30+
*/
31+
class Solution {
32+
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
33+
List<List<Integer>> result = new ArrayList<>();
34+
if(root == null) return result;
35+
executor(root, result, 0);
36+
return result;
37+
}
38+
39+
public void executor(TreeNode node,List<List<Integer>> result,int high){
40+
if(node == null) return;
41+
if(result.size() <= high) result.add(new ArrayList<>());
42+
if(high % 2 == 0){
43+
result.get(high).add(node.val);
44+
}else {
45+
result.get(high).add(0,node.val);
46+
}
47+
executor(node.left, result, high+1);
48+
executor(node.right, result, high+1);
49+
}
50+
}
51+
```

0 commit comments

Comments
 (0)