68-02 二叉搜索树的最近公共祖先
题目
对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
C++ 题解
根据BST特点,节点共三种情况:
p,q都在左子树(二者的值都小于根的值)
p,q都在右子树 (二者的值都大于根的值)
p,q分别在左右子树(此时最近公共祖先为root)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if( root == nullptr )
return nullptr;
TreeNode* res;
if( p->val < root->val && q->val < root->val )
res = lowestCommonAncestor( root->left, p, q );
else if( p->val > root->val && q->val > root->val )
res = lowestCommonAncestor( root->right, p, q );
else
res = root;
return res;
}
};
python 题解
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
if root.val > p.val and root.val > q.val:
res = self.lowestCommonAncestor(root.left,p,q)
elif root.val < p.val and root.val < q.val:
res = self.lowestCommonAncestor(root.right,p,q)
else:
res =root
return res