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 5For 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.
题意
给定一棵二分搜索树和两个节点,寻找这两个节点的最近公共祖先。
注意
二叉搜索树的性质:
每个节点的键值大于左孩子;每个节点的键值小于右孩子;以左右孩子为根的子树仍为二分搜索树二叉树的操作:
插入 insert,查找 find, 删除 delete
最大值,最小值 minimum, maximum
前驱,后继 successor, predecessor
上界,下界 floor, ceil
某个元素的排名 rank
寻找第k大(小)元素 select
思路
见代码注释
代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL)
{
return NULL;
}
//p和q在二分搜索树中的左侧,那么在左侧寻找其公共祖先
if(p->val < root->val&& q->val < root->val)
{
return lowestCommonAncestor(root->left,p,q);
}
//p和q在二分搜索树中的右侧,那么在右侧寻找其公共祖先
if(p->val > root->val&& q->val > root->val)
{
return lowestCommonAncestor(root->right,p,q);
}
//若不然,不是上述的两种情况,一个是>=root值,一个是<=root值,这种情况下
//p,q的公共祖先是root,含有二种情况
//1.p<root ,q>root 即p和q在root的两侧
//2.p=root或者q=root
//注意 p和q能否都在树上,p和q的有效性
return root;
}
};