Approach
My idea is to sweep the tree and collect the maxDeep and maxCnt, and then do the second pass to track the count for maxDeep, and return the first node that has cnt reaching maxCnt`. Code in code-1.
After this I ask AI to have an optimized version, and it give me code-2, where we can directly store the depest node, and its ancestors. when left and right subtree have the same deep, we can return the current subtree and the deep+1, else we return the best solution among two subtree.
Code-1: two-pass DFS
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
if(root == nullptr) return nullptr;
int maxLevel = -1;
int maxCnt = 0;
getCount(root, 0, maxLevel, maxCnt);
TreeNode* maxNode = nullptr;
search(root, 0, maxLevel, maxCnt, maxNode);
return maxNode;
}
void getCount(TreeNode* root, int level, int& maxLevel, int& maxCnt) {
if(maxLevel < level) {
maxLevel = level;
maxCnt = 1;
} else if(maxLevel == level) {
++maxCnt;
}
if(root->left) getCount(root->left, level+1, maxLevel, maxCnt);
if(root->right) getCount(root->right, level+1, maxLevel, maxCnt);
}
int search(TreeNode* root, int level, const int& maxLevel, const int& maxCnt, TreeNode*& maxNode) {
if(maxNode != nullptr) return 0;
int cnt = (maxLevel == level) ? 1 : 0;
if(root->left) cnt += search(root->left, level+1, maxLevel, maxCnt, maxNode);
if(root->right) cnt += search(root->right, level+1, maxLevel, maxCnt, maxNode);
if(maxNode != nullptr) return 0;
if(cnt == maxCnt) {
maxNode = root;
}
return cnt;
}
};
Code-2: single-pass DFS
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(root).second;
}
pair<int, TreeNode*> dfs(TreeNode* node) {
if (!node) return {0, nullptr};
auto [dl, al] = dfs(node->left);
auto [dr, ar] = dfs(node->right);
if (dl == dr) return {dl + 1, node};
if (dl > dr) return {dl + 1, al};
return {dr + 1, ar};
}
};