题目
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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes `2` and `8` is `6`.
Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes `2` and `4` is `2`, since a node can be a descendant of itself according to the LCA definition.
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the BST.
解析
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
以上是二叉查找树的定义,可以发现其前序遍历是由小到大的排列。因此,
对于求公共祖先,可以依据以下事实:
(1)如果p,q的最大值都比根结点要小,那么其公共祖先在左子树上;
(2)如果p,q的最小值都比根结点要大,那么其公共祖先在右子树上;
(3)如果p和q分居在root的左右两侧,那么其公共祖先为根结点。
其它结点进行递归求解。
代码(C语言)
struct TreeNode* lowestCommonAncestor(struct TreeNode* root,
struct TreeNode* p, struct TreeNode* q) {
if (root == NULL)
return NULL;
int minNum = p->val > q->val ? q->val : p->val;
int maxNum = p->val > q->val ? p->val : q->val;
if (minNum > root->val) {
return lowestCommonAncestor(root->right, p, q);
} else if (maxNum < root->val) {
return lowestCommonAncestor(root->left, p, q);
}
return root;
}
网友评论