Wednesday, January 14, 2015

Binary Tree Level Order Traversal II (LeetCode Tree)

Question: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]

Idea: Breadth-first search. Use a queue to maintain the nodes in the next level. Whenever a level is visited, insert it at the front of the result, then the result will be bottom-up order.

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

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

No comments:

Post a Comment