題目
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),(又:二叉搜索樹,二叉排序樹)它或者是一棵空樹,或者是具有下列性質(zhì)的二叉樹: 若它的左子樹不空,則左子樹上所有結(jié)點的值均小于它的根結(jié)點的值; 若它的右子樹不空,則右子樹上所有結(jié)點的值均大于它的根結(jié)點的值; 它的左、右子樹也分別為二叉排序樹。
以上是二叉查找樹的定義,可以發(fā)現(xiàn)其前序遍歷是由小到大的排列。因此,
對于求公共祖先,可以依據(jù)以下事實:
(1)如果p,q的最大值都比根結(jié)點要小,那么其公共祖先在左子樹上;
(2)如果p,q的最小值都比根結(jié)點要大,那么其公共祖先在右子樹上;
(3)如果p和q分居在root的左右兩側(cè),那么其公共祖先為根結(jié)點。
其它結(jié)點進行遞歸求解。
代碼(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;
}