Problem
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).
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]
]
Note
Solution
public class Solution {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList();
if (root == null) return res;
boolean LR = true;
Stack<TreeNode> stack = new Stack();
stack.push(root);
while (!stack.isEmpty()) {
Stack<TreeNode> curStack = new Stack();
ArrayList<Integer> curList = new ArrayList();
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
curList.add(cur.val);
if (LR) {
if (cur.left != null) curStack.push(cur.left);
if (cur.right != null) curStack.push(cur.right);
}
else {
if (cur.right != null) curStack.push(cur.right);
if (cur.left != null) curStack.push(cur.left);
}
}
stack = curStack;
res.add(curList);
LR = !LR;
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。