LeetCode | 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]
]

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //与层序遍历的思想一模一样,唯一差别是在添加thisLevelList到result时使用addFirst添加到头位置,而不是用add()顺序添加
 //遍历顺序[3] [9,20] [15,7] add之后->      { [3] [9,20] [15,7] } 
 //遍历顺序[3] [9,20] [15,7] addFirst之后-> { [15,7] [9,20] [3] } 正好符合题意要求
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();  //注意result的类型是LinkedList<List<Integer>>,
        if(root==null) return result;                        //而不能是List<List<Integer>>,不然向上转型时会把addFirst()方法转没
        
        Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        nodeQueue.add(root);
        TreeNode nextLevelStarter;
        
        while(!nodeQueue.isEmpty()){
            List<Integer> thisLevelList = new LinkedList<Integer>();
            nextLevelStarter = null;
            
            while(nodeQueue.isEmpty()==false && nodeQueue.peek()!=nextLevelStarter){
                TreeNode curNode = nodeQueue.remove();
                thisLevelList.add(curNode.val);
                if(curNode.left!=null) nodeQueue.add(curNode.left);
                if(curNode.right!=null) nodeQueue.add(curNode.right);
                
                if(nextLevelStarter==null){
                    if(curNode.left!=null){
                        nextLevelStarter = curNode.left;
                    }else if(curNode.right!=null){
                        nextLevelStarter = curNode.right;
                    }
                }
            }
            
            result.addFirst(thisLevelList);     //与层序遍历代码唯一的差别!!!!!!
        }                                       
        return result;
    }
}


 


 

posted @ 2014-11-22 14:04  Mr.do  阅读(121)  评论(0编辑  收藏  举报