MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / zigzagLevelOrder

Method zigzagLevelOrder

TreeZigZagBinaryTree.java:2–36  ·  view source on GitHub ↗
(TreeNode root)

Source from the content-addressed store, hash-verified

1class Solution {
2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
3
4 List<List<Integer>> list = new ArrayList<List<Integer>>();
5
6 if(root == null) return list;
7
8 boolean flag = true;
9
10 Queue<TreeNode> queue = new LinkedList<TreeNode>();
11
12 queue.add(root);
13
14 while(!queue.isEmpty())
15 {
16 int level = queue.size();
17 List<Integer> subList = new ArrayList<>();
18 for(int i=0;i<level;i++)
19 {
20 if(queue.peek().left!=null) queue.add(queue.peek().left);
21 if(queue.peek().right!=null) queue.add(queue.peek().right);
22 if(flag==true)
23 {
24 subList.add(queue.remove().val);
25 }
26 else
27 {
28 subList.add(0,queue.remove().val);
29 }
30 }
31 flag = !flag;
32 list.add(subList);
33 }
34 return list;
35
36 }
37}

Callers

nothing calls this directly

Calls 2

addMethod · 0.45
isEmptyMethod · 0.45

Tested by

no test coverage detected