clueless coding // TODO: be smarter

LeetCode 102. Binary Tree Level Order Traversal II: Java Solution



Problem Statement


Given a binary tree, return the level order traversal of its nodes’ values.

In other words, traverse the tree from left to right, level by level.

Function Signature (Java):
  public List<List<Integer>> levelOrderBottom(TreeNode root)

Inputs:
    3
   / \
  9  20
     / \
    15  7

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



TL;DR Code Solution


public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> res = new LinkedList<List<Integer>>();
    dfs(res, root, 0);
    return res;
}

public void dfs(List<List<Integer>> res, TreeNode root, int depth) {

    if (root == null) {
        return;
    }

    if (depth == res.size()) {
        res.add(0, new LinkedList<Integer>());
    }

    dfs(res, root.left, depth + 1);
    dfs(res, root.right, depth + 1);
    res.get(res.size() - depth - 1).add(root.val);

}