235. 二叉搜索树的最近公共祖先
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 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, 因为根据定义最近公共祖先节点可以为节点本身。
解题代码如下:
很不错的一个题目,感兴趣的,可以学习学习,有几个细节需要我们去细心的处理:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* re;
int find;
int dfs(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
if(root){
int l=dfs(root->left,p,q);
int r=dfs(root->right,p,q);
if(l==1&&r==1){
re=root;
return 0;
}
if((l==1||r==1)&&(root==p||root==q)){
re=root;
return 0;
}
if(root==p||root==q){
return 1;
}
if(r==1||l==1){
return 1;
}
return 0;
}
else{
return 0;
}
}
// void dfs2(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
// if(root){
// dfs2(root->left,p,q);
// dfs2(root->right,p,q);
// if(root==p||root==q){
// find++;
// }
// if(find==2){
// re=root;
// find=0;
// }
// }
// }
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
re=NULL;
dfs(root,p,q);
return re;
}