题目描述:
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉搜索树中。
此题思路:题目给出一个二叉搜索树,需要我们找到p和q的最近公共祖先,那么我们就一定要找到他们最开始的分割点,这个分割点就是我们要找的节点。那么这个问题就可以分几种情况讨论
1、p和q都在当前节点的右子树上,则遍历右子树
2、p和q都在当前节点的左子树上,则遍历左子树
3、如果上述两种情况都不满足,则说明找到了最近的公共分割点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//树是空树
if(root==NULL)
return NULL;
//遍历二叉搜索树
int num1=p->val,num2=q->val;
//两个节点都在右子树上,遍历右子树
if(num1>root->val&&num2>root->val){
return lowestCommonAncestor(root->right,p,q);
}
//两个节点都在左子树上,遍历左子树
if(num1<root->val&&num2<root->val){
return lowestCommonAncestor(root->left,p,q);
}
else
return root;
}
};
时间复杂度:O(n),遍历树所消耗的时间=树节点个数*访问每个节点所消耗的时间。
空间复杂度:O(n),递归栈,栈的深度就是树的深度
此题还可以采用递推的形式,贴一个网上的代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//想法,遍历整棵树,将树的所有路径都得到,然后再根据给定的节点,查找所有路径,找到最近公共祖先
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int pVal = p->val;
// Value of q;
int qVal = q->val;
// Start from the root node of the tree
TreeNode* node = root;//声明树指针
// Traverse the tree
while (node != NULL) {
// Value of ancestor/parent node.
int parentVal = node->val;
if (pVal > parentVal && qVal > parentVal) {
// If both p and q are greater than parent
node = node->right;
} else if (pVal < parentVal && qVal < parentVal) {
// If both p and q are lesser than parent
node = node->left;
} else {
// We have found the split point, i.e. the LCA node.
return node;
}
}
return NULL;
}
};