Created
September 2, 2013 03:00
-
-
Save charlespunk/6408864 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). | |
For example: | |
Given binary tree {3,9,20,#,#,15,7}, | |
3 | |
/ \ | |
9 20 | |
/ \ | |
15 7 | |
return its zigzag level order traversal as: | |
[ | |
[3], | |
[20,9], | |
[15,7] | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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>> all = new ArrayList<ArrayList<Integer>>(); | |
Stack<TreeNode> current = new Stack<TreeNode>(); | |
Stack<TreeNode> next = new Stack<TreeNode>(); | |
boolean order = true; | |
if(root != null) current.push(root); | |
while(!current.isEmpty()){ | |
ArrayList<Integer> one = new ArrayList<Integer>(); | |
while(!current.isEmpty()){ | |
TreeNode node = current.pop(); | |
one.add(node.val); | |
if(order){ | |
if(node.left != null) next.push(node.left); | |
if(node.right != null) next.push(node.right); | |
} | |
else{ | |
if(node.right != null) next.push(node.right); | |
if(node.left != null) next.push(node.left); | |
} | |
} | |
all.add(one); | |
Stack<TreeNode> swap = current; | |
current = next; | |
next = swap; | |
next.clear(); | |
order = !order; | |
} | |
return all; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment