Friday, March 6, 2015

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]
]
Solution: BFS
和Binary Tree Level Order Traversal一样,最后reverse一下list得到bottom-up结果.
时间上和空间上仍是O(n)。
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList> levelOrderBottom(TreeNode root) {
        ArrayList> result = new ArrayList>();
        
        if(root == null)
            return result;
        
        LinkedList queue = new LinkedList();
        queue.add(root);
        
        int curLevCount = 1;
        int nextLevCount = 0;
        
        ArrayList levelRes = new ArrayList();
        ArrayList> list = new ArrayList>();
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            curLevCount--;
            levelRes.add(cur.val);
            
            if(cur.left != null) {
                queue.add(cur.left);
                nextLevCount++;
            }
            
            if(cur.right != null) {
                queue.add(cur.right);
                nextLevCount++;
            }
            
            if(curLevCount == 0) {
                curLevCount = nextLevCount;
                nextLevCount = 0;
                list.add(levelRes);
                levelRes = new ArrayList();
            }
        }
        
        //reverse the list
        for(int i = list.size() - 1; i >= 0; i--) {
            result.add(list.get(i));
        }
        
        return result;
    }
}

No comments:

Post a Comment