题目详情,链接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) {
int pval = p->val, qval = q->val, rootval = root->val;
//注意是二叉搜索树,右孩子的值大于父节点,左孩子的值小于父节点
if((pval < rootval) && (qval < rootval)){
//p和q都在左子树上
return lowestCommonAncestor(root->left, p, q);
}else if((pval > rootval) && (qval > rootval)){
//p和q都在右子树上
return lowestCommonAncestor(root->right, p, q);
}
//p和q分别在左子树和右子树上
return root;
}
};
运行结果