Saturday, March 1, 2014

Leetcode: Binary Tree Zigzag Level Order Traversal


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]
]

Solution

We use a variant of BFS with two stacks, one for this level one for the next one. As we traverse one level we add the children into the next level stack, once a level is traversed the next level stack becomes the actual one.

/**
 * Definition for binary tree
 * 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>> solution = new ArrayList<List<Integer>>();
        ArrayDeque<TreeNode> thisLevel = new ArrayDeque<TreeNode>();
        boolean leftToRight = true;
        if(root != null)
            thisLevel.add(root);
        while(!thisLevel.isEmpty())
        {
            List<Integer> level = new ArrayList<Integer>();
            ArrayDeque<TreeNode> nextLevel = new ArrayDeque<TreeNode>();
            while(!thisLevel.isEmpty())
            {
                TreeNode temp = thisLevel.pop();
                level.add(temp.val);
                if(leftToRight)
                {
                    if(temp.left != null)
                        nextLevel.push(temp.left);
                    if(temp.right != null)
                        nextLevel.push(temp.right);
                }
                else
                {
                    if(temp.right != null)
                        nextLevel.push(temp.right);
                    if(temp.left != null)
                        nextLevel.push(temp.left);
                }
            }
            leftToRight = !leftToRight;
            thisLevel = nextLevel;
            solution.add(level);
        }
        return solution;
    }
}

No comments :

Post a Comment