题目
题目链接
题目描述
代码实现
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;
}
};
思路分析
1、当root节点为空,或者节点等于p或者等于q的时候,就返回root。这也是递归的出口。
2、分别向左子树和右子树去找p或q。
3、当左子树没有找到,就返回右节点。同理,当右子树没有找到,就返回左节点。
4、当左子树和右子树都找到了,就说明,当前root就是他们的最近公共祖先,返回root。