
解法一 递归
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root ==q) return root;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};

这篇博客介绍了如何使用递归方法在二叉树中找到两个节点的最低公共祖先。代码实现中,当根节点为空或者等于目标节点之一时返回该节点,通过分别遍历左子树和右子树来寻找公共祖先。
475

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



