0 ms JS/C++. DFS. Beats 100.00%
ApproachDFS. Check the depth of the left and right child, if they are equal to the maximum depth, then the node is the lca(Lowest Common Ancestor) of Deepest Le
# Approach
DFS. Check the depth of the left and right child, if they are equal to the maximum depth, then the node is the `lca`(Lowest Common Ancestor) of Deepest Leaves. The solution is the same as [1123. Lowest Common Ancestor of Deepest Leaves](https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/solutions/6614672/0-ms-jsc-dfs-beats-10000-by-nodeforce-x7wp).

![1.png](https://assets.leetcode.com/users/images/8164f336-62f1-4f84-aa7f-d30a36fb997b_1743767049.8419197.png)

![2.png](https://assets.leetcode.com/users/images/bf8e5e6b-f5ee-47f7-a907-5d8db7594a5e_1743767059.5078492.png)

# Complexity
- Time complexity: $$O(n)$$.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(n)$$, because of recursion.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code

```cpp []
class Solution {
public:
    static TreeNode* subtreeWithAllDeepest(TreeNode* r) {
        int maxDepth = -1;
        TreeNode* lca = nullptr;
        const function<int(TreeNode*, int)> dfs = [&maxDepth, &lca, &dfs](TreeNode* n, int d) {
            const int dleft = n->left ? dfs(n->left, d + 1) : d;
            const int dright = n->right ? dfs(n->right, d + 1) : d;
            if (d > maxDepth) maxDepth = d;
            if (dleft == maxDepth && dright == maxDepth) lca = n;
            return max(dleft, dright);
        };
        dfs(r, 0);
        return lca;
    }
};
```
```javascript []
const subtreeWithAllDeepest = (r) => {
    let maxDepth = -1;
    let lca = null;
    const dfs = (n, d) => {
        const dleft = n.left ? dfs(n.left, d + 1) : d;
        const dright = n.right ? dfs(n.right, d + 1) : d;
        if (d > maxDepth) maxDepth = d;
        if (dleft === maxDepth && dright === maxDepth) lca = n;
        return Math.max(dleft, dright);
    };
    dfs(r, 0);
    return lca;
};
```
['Tree', 'Depth-First Search', 'Recursion', 'C', 'Binary Tree', 'C++', 'TypeScript', 'JavaScript']