Wednesday, February 12, 2014

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

Solution:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> solution = new ArrayList<List<Integer>>();
        ArrayList<TreeNode> thisLevel = new ArrayList<TreeNode>();
        if (root!=null)
            thisLevel.add(root);
        while(thisLevel.size()>0)
        {
            ArrayList<Integer> thisLevelNumbers = new ArrayList<Integer>();
            ArrayList<TreeNode> nextLevel = new ArrayList<TreeNode>();
            for(TreeNode tempNode: thisLevel)
            {
                thisLevelNumbers.add(tempNode.val);
                if (tempNode.left != null)
                    nextLevel.add(tempNode.left);
                if (tempNode.right != null)
                    nextLevel.add(tempNode.right);
            }
            solution.add(0, thisLevelNumbers);
            thisLevel = nextLevel;
        }
        return solution;
    }
}

No comments :

Post a Comment