Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * use depth to get the list to add the values belong to that level.
 */
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        r(root, 0);
        return res;
    }
    
    private void r(TreeNode root, int depth) {
        if (root == null) return;
        List<Integer> level = res.size() > depth ? res.get(depth):new ArrayList<>();
        if (res.size() == depth) res.add(level);
        level.add(root.val);
        r(root.left, depth + 1);
        r(root.right, depth + 1);
    }
}