Leetcode(103) Binary Tree Zigzag Level Order Traversal

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
41
class 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
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
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
int level = 1;
Queue<TreeNode> q = new LinkedList<>();
Stack<TreeNode> s = new Stack<>();
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
List<Integer> tmplist = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode tmp = q.poll();
tmplist.add(tmp.val);
if(tmp.left!=null){
q.offer(tmp.left);
}
if(tmp.right!=null){
q.offer(tmp.right);
}
}
if(level%2==0){
for(int i = 0;i<tmplist.size()/2;i++){
int tmp = tmplist.get(i);
tmplist.set(i,tmplist.get(tmplist.size() - i - 1));
tmplist.set(tmplist.size() - i - 1,tmp);
}
res.add(tmplist);
}
else{
res.add(tmplist);
}
level++;
}
return res;
}
}