https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
要点是如果root是在p和q之间的值,意味着已经找到了最近公共祖先
/**
* 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;
}
};
标签:right,TreeNode,val,二叉,return,235,root,leetcode,left From: https://www.cnblogs.com/lxl-233/p/18181186