-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path103.binary-tree-zigzag-level-order-traversal.java
More file actions
42 lines (40 loc) · 1.13 KB
/
Copy path103.binary-tree-zigzag-level-order-traversal.java
File metadata and controls
42 lines (40 loc) · 1.13 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null)
return res;
zigzag(root, res, 0, 0);
return res;
}
public void zigzag(TreeNode root, List<List<Integer>> res, int way, int ind){
if(root == null)
return;
ArrayList<Integer> tmp = new ArrayList<Integer>();
if(res.size() == ind)
res.add(ind, new ArrayList<Integer>());
if(way == 0){
res.get(ind).add(root.val);
way = 1;
}else{
way = 0;
res.get(ind).add(0, root.val);
}
zigzag(root.left, res, way,ind+1);
zigzag(root.right, res, way,ind+1);
}
}