Skip to content

366. Find Leaves of Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  vector<vector<int>> findLeaves(TreeNode* root) {
    vector<vector<int>> ans;

    depth(root, ans);
    return ans;
  }

 private:
  // Returns the depth of the root (0-indexed).
  int depth(TreeNode* root, vector<vector<int>>& ans) {
    if (root == nullptr)
      return -1;

    const int l = depth(root->left, ans);
    const int r = depth(root->right, ans);
    const int h = 1 + max(l, r);
    if (ans.size() == h)  // Meet a leaf.
      ans.push_back({});

    ans[h].push_back(root->val);
    return h;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public List<List<Integer>> findLeaves(TreeNode root) {
    List<List<Integer>> ans = new ArrayList<>();

    depth(root, ans);
    return ans;
  }

  // Returns the depth of the root (0-indexed).
  private int depth(TreeNode root, List<List<Integer>> ans) {
    if (root == null)
      return -1;

    final int l = depth(root.left, ans);
    final int r = depth(root.right, ans);
    final int h = 1 + Math.max(l, r);
    if (ans.size() == h) // Meet a leaf.
      ans.add(new ArrayList<>());

    ans.get(h).add(root.val);
    return h;
  }
}