LeetCode-107 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,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

The trick in this problem is to use Collection.reverse(<List>) to reverse the result, and List.get(index) to get the list of the same level.
It is important to record the level of nodes in the helper function.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        helper(root, 0, res);
        Collections.reverse(res);
        return res;
    }

    // record the level of this node 
    public void helper(TreeNode root, int level, List<List<Integer>> list){
        if(root!=null){
            if(list.size()>level){
                // use get(index) to retrieve the list of this level
                list.get(level).add(root.val);
            }else{
                List<Integer> newList = new ArrayList<>();
                newList.add(root.val);
                list.add(newList);
            }
            helper(root.left, level+1, list);
            helper(root.right, level+1, list);
        } 
    }
}