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.
给定一个二叉搜索树,找到两个节点的最小祖先
由于二叉搜索树性质:一个节点的值大于左边所有节点,小于右边所有节点,遍历该二叉搜索树:
1. 根节点的值大于两个节点中大的,则继续向右侧节点遍历
2. 根节点值小于左侧节点中小的,继续向左侧节点遍历
3. 一旦出现根节点值等于两个值其中一个,或者根节点的值大于小值,小于大值,则根节点为所得结果
/**
* 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) {
struct TreeNode* result = NULL;
struct TreeNode* t = NULL;
struct TreeNode* big = NULL;
struct TreeNode* small = NULL;
t = root;
if(p->val >= q->val)
{
big = p;
small = q;
}
else
{
big = q;
small = p;
}
while(t != NULL)
{
if(t->val > big->val)
{
t = t->left;
continue;
}
if(t->val < small->val)
{
t = t->right;
continue;
}
if(t->val == big->val || t->val == small->val || (t->val >= small->val && t->val <= big->val))
{
result = t;
break;
}
}
return result;
}
来源:https://www.cnblogs.com/Anthony-Wang/p/5102481.html