-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary-tree-zigzag-level-order-traversal
40 lines (40 loc) · 1.35 KB
/
binary-tree-zigzag-level-order-traversal
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
/**
* Definition for binary tree
* 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>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
int level = 0;
stack1.push(root);
while(!stack1.isEmpty() || !stack2.isEmpty()){
List<Integer> row = new ArrayList<Integer>();
if (!stack1.isEmpty()){
while (!stack1.isEmpty()){
TreeNode node = stack1.pop();
row.add(node.val);
if (node.left!=null) stack2.push(node.left);
if (node.right!=null) stack2.push(node.right);
}
}
else if (!stack2.isEmpty()){
while (!stack2.isEmpty()){
TreeNode node = stack2.pop();
row.add(node.val);
if (node.right!=null) stack1.push(node.right);
if (node.left!=null) stack1.push(node.left);
}
}
result.add(row);
}
return result;
}
}