Description:
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7]
,1
2
3
4
5 3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:1
2
3
4
5[
[3],
[20,9],
[15,7]
]
解法:
这道题需要仔细一点,虽然思路很简单,但是有点绕。要实现之字形走位,因为相邻行的方向不同,考虑使用两个栈进行操作,并且两个栈的进栈顺序也不同,一个先进右节点,一个先进左节点,具体代码如下: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
30
31
32
33
34
35
36
37
38
39
40
41class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {
return result;
}
Stack<TreeNode> s1 = new Stack<TreeNode>();
Stack<TreeNode> s2 = new Stack<TreeNode>();
s1.push(root);
while (!s1.empty() || !s2.empty()) {
if (s2.empty()) {
List<Integer> tmp = new ArrayList<Integer>();
while (!s1.empty()) {
TreeNode now = s1.pop();
if (now.left != null) {
s2.push(now.left);
}
if (now.right != null) {
s2.push(now.right);
}
tmp.add(now.val);
}
result.add(tmp);
} else {
List<Integer> tmp = new ArrayList<Integer>();
while (!s2.empty()) {
TreeNode now = s2.pop();
if (now.right != null) {
s1.push(now.right);
}
if (now.left != null) {
s1.push(now.left);
}
tmp.add(now.val);
}
result.add(tmp);
}
}
return result;
}
}
另一种思路:层序遍历,然后对于某些层在输出时翻转list即可:
1 | /** |