forked from udit034/LeetCode_Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.Binary Tree Zigzag Level Order Traversal.java
58 lines (48 loc) · 1.43 KB
/
Solution.Binary Tree Zigzag Level Order Traversal.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
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public class TreeNodeL
{
TreeNode n;
int l;
public TreeNodeL( TreeNode a, int b )
{
this.n = a;
this.l = b;
}
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if( root == null )
return new ArrayList<>();
List<TreeNodeL> q = new ArrayList<TreeNodeL>();
List<List<Integer>> res = new ArrayList<>();
q.add( new TreeNodeL( root, 0 ) );
while( !q.isEmpty() )
{
TreeNodeL curr = q.remove(0);
if( curr.l < res.size() )
res.get( curr.l ).add( curr.n.val );
else
{
res.add( curr.l, new ArrayList<Integer>() );
res.get( curr.l ).add( curr.n.val );
}
if( curr.n.left != null )
q.add( new TreeNodeL( curr.n.left, curr.l + 1 ) );
if( curr.n.right != null )
q.add( new TreeNodeL( curr.n.right, curr.l + 1 ) );
}
for( int i = 1; i < res.size(); i = i + 2 )
{
Collections.reverse( res.get(i) );
}
return res;
}
}