[LintCode/LeetCode] Binary Tree Zigzag Level Order Traversal

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).node

Example

Given binary tree {3,9,20,#,#,15,7},code

3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:it

[
  [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;
    }
}
相關文章
相關標籤/搜索