@snuffles
2019-04-04T08:37:09.000000Z
字数 996
阅读 882
树
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
解:p,q可以都在左子树,都在右子树或者一边一个。
用递归来解
非递归写法,用一个循环来判断0.98%,0%
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;
}
递归写法 //0.98%,0%
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
TreeNode* res;
if(root->val > max(p->val,q->val)){
res = lowestCommonAncestor(root->left,p,q);
}
else if(root->val < min(p->val,q->val)){
res = lowestCommonAncestor(root->right,p,q);
}
else res = root;
return res;
}
//递归写法// 0.98%,0%
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if( root == NULL) return NULL;
TreeNode * res;
if( p->val < root->val && q->val < root ->val){
res = lowestCommonAncestor(root->left,p,q);
}
else if( p->val > root->val && q->val > root ->val){
res = lowestCommonAncestor(root->right,p,q);
}
else res = root;
return res;
}
};