与《1123. 最深叶节点的最近公共祖先》题相同。
求最深叶节点的lca就是求具有所有最深节点的最小子树。
思路1:一遍dfs求最大深度,再来一遍dfs求这些深度最大的点的lca
class Solution {
public:
int getDepth(TreeNode* root)
{
if (root)
{
int left = getDepth(root->left);
int right = getDepth(root->right);
return max(left, right)+1;
}
return -1;
}
TreeNode* lca(TreeNode* root, int depth, int curdepth)
{
if (curdepth == depth || root == NULL)
return root;
TreeNode* left = lca(root->left, depth, curdepth+1);
TreeNode* right = lca(root->right, depth, curdepth+1);
if (left && right)
return root;
else if (left)
return left;
else
return right;
}
TreeNode* lcaDeepestLeaves(TreeNode* root) {
int depth = getDepth(root);
TreeNode* res = lca(root, depth, 0);
return res;
}
};
思路2:只做一遍递归,同时记录节点地址和节点的深度。如果一个节点的左右子树中包含最深节点的深度不一样,返回拥有更大深度节点的子树的根节点和最大深度;如果深度一样,则返回该节点,以及左右子树中深度最大节点的深度
class Solution {
public:
pair<TreeNode*, int> dfs(pair<TreeNode*, int> root)
{
if (root.first == NULL)
return make_pair(nullptr, 0);
pair<TreeNode*, int> left = dfs(make_pair(root.first->left, root.second+1));
pair<TreeNode*, int> right = dfs(make_pair(root.first->right, root.second+1));
if (left.second > right.second) return left;
else if (left.second < right.second) return right;
else return make_pair(root.first, !left.first ? root.second : left.second);
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(make_pair(root, 0)).first;
}
};
思路3(官方解法):只做一遍递归,同时记录节点地址和节点到最深节点的距离(节点的高度)。如果一个节点的左右子树高度不同,返回高度更大子树的根节点和该节点的高度;如果高度一样,则返回该节点和该节点的高度。
本文对比了三种高效解决最深叶节点最近公共祖先问题的算法思路,包括深度优先遍历结合最大深度计算、一次递归记录节点深度与地址,以及官方推荐的仅遍历一次记录节点距离的方法。详细解析了每种方法的实现细节和优势。
2612

被折叠的 条评论
为什么被折叠?



