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

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

---

/**
 * 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) {
        
        ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> curList = new ArrayList<Integer>();
        ArrayList<TreeNode> curNodeList = new ArrayList<TreeNode>();
        
        // check
        if(root==null)  return rst;
        
        // init root
        curList.add(root.val);
        curNodeList.add(root);
        int level = 0;
        
        while(!curNodeList.isEmpty()){
            
            // add previous level to rst, reverse in odd level
            if(level %2 != 0)
                Collections.reverse(curList);
            rst.add(curList);
            
            // update
            ArrayList<TreeNode> preNodeList = curNodeList;
            curNodeList = new ArrayList<TreeNode>();
            curList = new ArrayList<Integer>();
           
            // go through the prevois level
            for(TreeNode n : preNodeList){
                if(n.left != null){
                     curNodeList.add(n.left);
                     curList.add(n.left.val);
                }
                if(n.right != null){
                    curNodeList.add(n.right);
                    curList.add(n.right.val);
                }
            }
            level++;
        }
        
        return rst;
        
    }
}

 

posted @ 2013-09-22 01:49  LEDYC  阅读(181)  评论(0)    收藏  举报