235. 二叉搜索树的最近公共祖先(leetcode)
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
明确函数的返回值和参数,返回最近公共祖先,没有就返回null
单层递归逻辑是:若按搜索树条件,递归左子树未查询到,递归右子树也未查询到,那么意味着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:
// 返回公共祖先节点,若没有则返回null
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr)return root;
if(root->val > p->val && root->val > q->val)
{
TreeNode* left = lowestCommonAncestor(root->left,p,q);
if(left!=nullptr)return left;
}
if(root->val < p->val && root->val < q->val)
{
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(right!=nullptr)return right;
}
// root在p和q中间
return root;
}
};

浙公网安备 33010602011771号