235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
给定一个二叉搜索树(BST),寻找该树上给定两结点的最小共同祖先(LCA)。
根据维基百科上LCA的定义:LCA
最小共同祖先定义为树T上关于两结点v和w的一个结点,v和w同时是这个结点的后代,并且这个结点尽可能靠下。
(我们可以把一个结点视为他自身的后代)
比如说:
上图中,结点2和结点8的最小共同祖先是6。再举个例子:结点2和结点4的最小共同祖先是2,因为根据LCA的定义一个结点可以是它自身的后代。
思路:可以考虑利用递归来解决。C程序中提供了一个根结点指针root,两个给定结点指针p和q。那么我们可以通过root的不断递归来找到LCA然后返回。由于题目给定了这是一个二叉搜索树,这意味着虽然我们不知道p和q在哪,但现在比较一下root->val,p->val,q->val,我们就能得到其大致方位。那么所有的可能就是p和q分别在root两边或者p和q同时在root的一边。可以发现,当p和q在root结点的左右两边时,此时的root结点即是我们需要的LCA,这也是递归的终点。当p和q同时在root的左边时,我们就要将root递归成root->left,从其左子树上重复进行前面的判断过程。p和q同时在右边同理。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if ((p->val < root->val) && (q->val < root->val)){
return lowestCommonAncestor(root->left, p, q);
}
else if ((p->val > root->val) && (q->val > root->val)){
return lowestCommonAncestor(root->right, p, q);
}
else return root;
}
# 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 p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root