class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {//返回最低公共祖先
if(root == NULL || p== NULL || q == NULL){
return NULL;
}
if(root == p || root == q){
return root;
}
TreeNode * left = lowestCommonAncestor(root->left,p,q);
TreeNode * right = lowestCommonAncestor(root->right,p,q);
if(left == NULL){//要么 p,q 有一或二,在右子树,要么都在根节点右子树
return right;
}
if(right == NULL ){//p,q有一个在左子树,或者都在左
return left;
}
return root;//左右都不为空,最低公共祖先
}
};
最低公共祖先
最新推荐文章于 2024-08-07 06:49:25 发布