Created
May 30, 2017 22:36
-
-
Save BiruLyu/1be235466463b4f5c3c354ded69aebdb to your computer and use it in GitHub Desktop.
This file contains 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
public class Solution { | |
public List<List<Integer>> zigzagLevelOrder(TreeNode root) { | |
List<List<Integer>> res = new ArrayList<>(); | |
if(root == null) return res; | |
Queue<TreeNode> q = new LinkedList<>(); | |
q.add(root); | |
boolean order = true; | |
int size = 1; | |
while(!q.isEmpty()) { | |
List<Integer> tmp = new ArrayList<>(); | |
for(int i = 0; i < size; ++i) { | |
TreeNode n = q.poll(); | |
if(order) { | |
tmp.add(n.val); | |
} else { | |
tmp.add(0, n.val); | |
} | |
if(n.left != null) q.add(n.left); | |
if(n.right != null) q.add(n.right); | |
} | |
res.add(tmp); | |
size = q.size(); | |
order = order ? false : true; | |
} | |
return res; | |
} | |
} |
This file contains 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 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; | |
dfs(root, 1, res); | |
return res; | |
} | |
private void dfs(TreeNode root, int level, List<List<Integer>> res) { | |
if (root == null) return; | |
if(res.size() < level) { | |
res.add(new ArrayList<Integer>()); | |
} | |
if(level % 2 == 0) { | |
res.get(level - 1).add(0, root.val); | |
} else { | |
res.get(level - 1).add(root.val); | |
} | |
dfs(root.left, level + 1, res); | |
dfs(root.right, level + 1, res); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment