明天就要放暑假了,只可惜研究生与暑假关系不大。下面就和大家来分享一下刚刷这道题的经验吧!
题目如下:
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.
题意分析:
给定一个二分搜索树与树中的两个节点,请找到这两个节点的最小公共祖先(父节点)。二分搜索树的定义为:父节点的值必须大于左节点的值同时小于右节点的值。
注:① 所有的节点值都是独一无二的;② p与q是不同节点,且存在于被给的二分搜索树中。
方法一(递归法)
由于本题给的树是二分搜索树,所以可借助二分搜索树的特性并分三种情况进行讨论:① 当p与q的节点值均小于根节点值时,此时p与q的公共祖先应在根节点的左子树中,所以需要对根节点的左子树进行递归调用;② 当p与q的节点值均大于根节点值时,此时p与q的公共祖先应在根节点的右子树中,所以需要对根节点的右子树进行递归调用;③ 当p与q的节点值一个大于(等于)根节点值,一个小于(等于)根节点值时,那么p与q的公共祖先必然为根节点,故直接返回根节点即可。
解题代码如下:
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
assert(p != NULL && q != NULL);
if (root == NULL) return NULL;
if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);
if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q);
return root;
}
};
提交后的结果如下:
方法二(优化方法一)
对方法一中的代码进行优化。
解题代码如下:
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
assert(p != NULL && q != NULL);
if (root == NULL) return NULL;
if(root->val > max(p->val, q->val)) return lowestCommonAncestor(root->left, p, q);
else if(root->val < min(p->val, q->val)) return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
提交后的结果如下:
方法三(非递归方法)
本题也可以采用while循环,根据所满足的条件不断更新当前的根节点,最终也可求得两个节点的最小公共祖先。
解题代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (true) {
if (root->val > max(p->val, q->val)) root = root->left;
else if (root->val < min(p->val, q->val)) root = root->right;
else break;
}
return root;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。