leetcode 106: Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal Sep 29 '12

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; }
 * }
 */
 
 //{1,2,3,4,5}
public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        //input check
        if(root==null) return res;
        
        Queue<TreeNode> q1 = new LinkedList<TreeNode>();
        Queue<TreeNode> q2 = new LinkedList<TreeNode>();
        
        q1.offer(root);
        ArrayList<Integer> level = new ArrayList<Integer>();
        
        int i=0;
        while( !q1.isEmpty()) {
            TreeNode n = q1.poll();
            level.add(n.val);
            
            if(n.left!=null) q2.offer(n.left);
            if(n.right!=null) q2.offer(n.right);
            
            if(q1.isEmpty()){
                if((i&1)==0){
                    res.add(level);
                } else {
                    Collections.reverse(level);
                    res.add(level);
                }
                Queue<TreeNode> temp = q1;
                q1 = q2;
                q2 = temp;
                level = new ArrayList<Integer>();
                ++i;
            }
        }
        return res;
    }
}


你可能感兴趣的:(leetcode 106: Binary Tree Zigzag Level Order Traversal)