-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeZigzagLevelOrderTraversal.java
41 lines (40 loc) · 1.14 KB
/
BinaryTreeZigzagLevelOrderTraversal.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
boolean zigzag=false;
while(!queue.isEmpty())
{
int iterator = queue.size();
List<Integer> sublist = new ArrayList<Integer>();
for(int i=0;i<iterator;i++)
{
TreeNode curr = queue.poll();
if(zigzag)
{
sublist.add(0,curr.val);
}
else
{
sublist.add(curr.val);
}
if(curr.left!=null) queue.add(curr.left);
if(curr.right!=null) queue.add(curr.right);
}
res.add(sublist);
zigzag=!zigzag;
}
return res;
}
}