Binary Tree Level Order Traversal II @LeetCode

2014-11-24 08:29:20 · 作者: · 浏览: 1
树的Level Order Traversal加上ArrayList翻转
package Level3;  
  
import java.util.ArrayList;  
import java.util.LinkedList;  
import java.util.Queue;  
  
import Utility.TreeNode;  
  
  
/** 
 * Binary Tree Level Order Traversal II  
 *  
 *  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], 
] 
confused what "{1,#,2,3}" means  > read more on how binary tree is serialized on OJ. 


OJ's Binary Tree Serialization: 
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 

Here's an example: 
   1 
  / \ 
 2   3 
    / 
   4 
    \ 
     5 
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 
 * 
 */  
public class S107 {  
  
    public static void main(String[] args) {  
  
    }  
  
    public ArrayList> levelOrderBottom(TreeNode root) {  
        ArrayList> ret = new ArrayList>();  
          
        if(root == null){  
            return ret;  
        }  
        Queue
queue = new LinkedList(); queue.add(root); ArrayList> alal = new ArrayList>(); ArrayList al = new ArrayList(); // 记录两个当前level和下一个level的node数目 int currentLevel = 1; int nextLevel = 0; while( !queue.isEmpty() ){ TreeNode cur = queue.remove(); currentLevel--; al.add(cur.val); if(cur.left != null){ queue.add(cur.left); nextLevel++; } if(cur.right != null){ queue.add(cur.right); nextLevel++; } if(currentLevel == 0){ alal.add(al); al = new ArrayList(); currentLevel = nextLevel; nextLevel = 0; } } // 翻转ArrayList for(int i=alal.size()-1; i>=0; i--){ ret.add(alal.get(i)); } return ret; } }