forked from mJackie/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 11
/
lc103.java
46 lines (43 loc) · 1.27 KB
/
lc103.java
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
package code;
/*
* 103. Binary Tree Zigzag Level Order Traversal
* 题意:蛇形层次遍历
* 难度:Medium
* 分类:Stack, Tree, Breadth-first Search
* 思路:层次遍历,加了个flag每次是在list头添加或尾添加
* Tips:Bingo!
*/
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class lc103 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> q = new ArrayDeque();
q.add(root);
boolean flag = true;
while(!q.isEmpty()){
int size = q.size();
List<Integer> ls = new ArrayList<>();
while(size>0){
TreeNode temp = q.remove();
if(flag) ls.add(temp.val);
else ls.add(0,temp.val); //在头部添加
if(temp.left!=null) q.add(temp.left);
if(temp.right!=null) q.add(temp.right);
size--;
}
res.add(ls);
flag = !flag;
}
return res;
}
}