題目
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é)點(diǎn)的值均小于它的根結(jié)點(diǎn)的值没佑; 若它的右子樹不空毕贼,則右子樹上所有結(jié)點(diǎn)的值均大于它的根結(jié)點(diǎn)的值; 它的左蛤奢、右子樹也分別為二叉排序樹鬼癣。
以上是二叉查找樹的定義,可以發(fā)現(xiàn)其前序遍歷是由小到大的排列啤贩。因此待秃,
對(duì)于求公共祖先,可以依據(jù)以下事實(shí):
(1)如果p,q的最大值都比根結(jié)點(diǎn)要小痹屹,那么其公共祖先在左子樹上章郁;
(2)如果p,q的最小值都比根結(jié)點(diǎn)要大,那么其公共祖先在右子樹上痢掠;
(3)如果p和q分居在root的左右兩側(cè)驱犹,那么其公共祖先為根結(jié)點(diǎn)嘲恍。
其它結(jié)點(diǎn)進(jìn)行遞歸求解。
代碼(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;
}