865. Smallest Subtree with all the Deepest Nodes
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
class Solution {
public:
pair<int, TreeNode*> dfs(TreeNode *cur) {
if (cur == nullptr) return {0, nullptr};
const auto l = dfs(cur->left), r = dfs(cur->right);
const auto dl = l.first, dr = r.first;
return {max(dl, dr) + 1, dl == dr ? cur : dl > dr ? l.second : r.second};
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(root).second;
}
};Last updated