题目连接:
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.
“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).”
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.
题目解释:
给定一个二叉查找树,找出给定两个节点的最小公共祖先,所谓的最小公共祖先指的是在一个子树T中包含v w两个子节点的最小的根节点(根节点可以是子节点本身),例如2和8的LCA为6,2和4的LCA是2。
解题方案:
在解题之前,我们必须要明白什么是二叉查找树(BST)?
二叉排序树是一颗空树或者是具有以下属性的树:
1. 若左子树不空,则左子树上所有结点的值均小于它的根结点的值; 2. 若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值; 3. 左、右子树也分别为二叉排序树; 4. 没有键值相等的节点。
也就是说:只要值比根节点的值小,那么这个节点一定在根节点的左子树种,只要是值比根节点的值大的,那么这个节点一定在根节点的右子树种,如果两个节点分列左右子树中,那么这个根节点就是这两个节点的LCA。
这就是我们的解题方案!
看完上面的描述我们很自然的就可以想到了这个题的解题思路:递归求解
1.如果两个节点都小于根节点,那么递归的去处理左子树。
2.如果两个节点都大于根节点,那么递归的去处理右子树。
3.递归出口:两个节点分落在根节点的两侧(包括某一个节点等于根节点的情况)那么直接返回该 根节点 即可。
OK,接下来就来看一下我的C语言实现:
C++
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
{
if (root == NULL)
{
return NULL;
}
int max = (p->val > q->val) ? p->val : q->val;
int min = (p->val < q->val) ? p->val : q->val;
if (max < root->val)
{
return lowestCommonAncestor(root->left, p, q);
}
if (min > root->val)
{
return lowestCommonAncestor(root->right, p, q);
}
return root;
}