题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目描述:
题解:
/**
* 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) {
if(root->val > p->val && root->val > q->val) //当前遍历的节点比p,q的值都大,祖先在当前节点的左子树
{
TreeNode *left = lowestCommonAncestor(root->left, p, q);
if(left != NULL)
return left;
}
if(root->val < p->val && root->val < q->val) //当前遍历的节点比p,q的值都小,祖先在当前节点的右子树
{
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(right != NULL)
return right;
}
return root;
}
};