https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/description/
好想好写的写法就是两次遍历
class Solution {
public:
int maxDep(TreeNode* root) {
if (!root) return 0;
return max(maxDep(root->left), maxDep(root->right)) + 1;
}
TreeNode* find(TreeNode* root, int cur_dep, int max_dep) {
if(!root) return NULL;
TreeNode* left = find(root->left, cur_dep+1, max_dep);
TreeNode* right = find(root->right, cur_dep+1, max_dep);
if (cur_dep == max_dep) {
return root;
}
if (left && right) return root;
if (left) return left;
if (right) return right;
return NULL;
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
if (!root) return root;
int max_dep = maxDep(root);
return find(root, 1, max_dep);
}
};
另外后续遍历的时候,子树深度 还有距离根节点的深度是可以同时获得的,于是能拿到总的深度,
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/146821/One-Traversal-C++-Simplest-one!!
这个解有意思
int utils(TreeNode *root, int c_d, int &max_d, TreeNode* &res) {
if(root == nullptr)
return 0;
int l = utils(root->left, c_d + 1, max_d, res);
int r = utils(root->right, c_d + 1, max_d, res);
int h = max(l, r);
if(l == r && c_d + h >= max_d) {
max_d = c_d + h;
res = root;
}
return h + 1;
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
TreeNode *res = root;
int c_d = 0, max_d = INT_MIN;
utils(root, c_d, max_d, res);
return res;
}