forked from guolinaileen/abc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Zigzag Level Order Traversal.java
45 lines (45 loc) · 1.36 KB
/
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
if(root==null) return list;
Stack<TreeNode> T=new Stack<TreeNode>();
Stack<TreeNode> S=new Stack<TreeNode>();
ArrayList<Integer> sub=new ArrayList<Integer>();
T.push(root);
boolean reverse=false;
while(!T.isEmpty())
{
TreeNode top=T.pop();
sub.add(top.val);
if(!reverse)
{
if(top.left!=null) S.push(top.left);
if(top.right!=null) S.push(top.right);
}else
{
if(top.right!=null) S.push(top.right);
if(top.left!=null) S.push(top.left);
}
if(T.isEmpty())
{
list.add(sub);
T=S;
S=new Stack<TreeNode>();
reverse=!reverse;
sub=new ArrayList<Integer>();
}
}
return list;
}
}