Thursday, January 15, 2015

Binary Tree Zigzag Level Order Traversal (LeetCode Tree)

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

Idea: Breadth-first search. Maintain a flag to reverse the direction of the next row.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public List<List<Integer>> zigzagLevelOrder(TreeNode root) {  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     if(root==null)  
       return result;  
     Queue<TreeNode> queue=new LinkedList<TreeNode>();  
     queue.offer(root);  
     boolean reverse=false;  
     while(queue.isEmpty()==false)  
     {  
       int queueSize=queue.size();  
       List<Integer> row=new ArrayList<Integer>();  
       for(int i=0;i<queueSize;i++)  
       {  
         TreeNode cur=queue.poll();  
         if(reverse==true)  
         {  
           row.add(0,cur.val);  
         }  
         else  
         {  
           row.add(cur.val);  
         }  
         if(cur.left!=null)  
           queue.offer(cur.left);  
         if(cur.right!=null)  
           queue.offer(cur.right);  
       }  
       result.add(row);  
       reverse=!reverse;  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment