题解:
递归三部曲:
1、确定递归函数的参数和返回值
参数为三个树结点,返回值为目标结点
2、确定递归终止条件
为空时返回
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) {
//二叉搜索树的有序性,只要当前结点在[p,q]之间即为最近公共祖先
if(root == NULL){
return NULL;
}
//递归遍历 寻找目标结点
//目标结点在右子树
if(root->val<p->val && root->val<q->val){
return lowestCommonAncestor(root->right,p,q);
}
//目标结点在左子树
if(root->val>p->val && root->val>q->val){
return lowestCommonAncestor(root->left,p,q);
}
//其他情况 就是结点值在p与q之间
return root;
}
};
迭代法:处理逻辑同上
/**
* 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) {
//迭代法
while(root){
if(root->val<p->val && root->val<q->val){
root = root->right;
}else if(root->val>p->val&& root->val>q->val){
root = root->left;
}else{
return root;
}
}
return NULL;
}
};