class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL) return root;
if(root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left != NULL && right != NULL) {
return root;
} else if(left != NULL && right == NULL) {
return left;
} else {
return right;
}
}
};
最近公共祖先
最新推荐文章于 2024-04-24 22:20:45 发布