Skip to content

865. Smallest Subtree with all the Deepest Nodes 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
struct T {
  TreeNode* lca;
  int depth;
};

class Solution {
 public:
  TreeNode* subtreeWithAllDeepest(TreeNode* root) {
    return dfs(root).lca;
  }

 private:
  T dfs(TreeNode* root) {
    if (root == nullptr)
      return {nullptr, 0};

    T l = dfs(root->left);
    T r = dfs(root->right);
    if (l.depth > r.depth)
      return {l.lca, l.depth + 1};
    if (l.depth < r.depth)
      return {r.lca, r.depth + 1};
    return {root, l.depth + 1};
  }
};
 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
26
27
28
class T {
  public TreeNode lca;
  public int depth;

  public T(TreeNode lca, int depth) {
    this.lca = lca;
    this.depth = depth;
  }
};

class Solution {
  public TreeNode subtreeWithAllDeepest(TreeNode root) {
    return dfs(root).lca;
  }

  private T dfs(TreeNode root) {
    if (root == null)
      return new T(null, 0);

    T l = dfs(root.left);
    T r = dfs(root.right);
    if (l.depth > r.depth)
      return new T(l.lca, l.depth + 1);
    if (l.depth < r.depth)
      return new T(r.lca, r.depth + 1);
    return new T(root, l.depth + 1);
  }
}