个人学习笔记:在二叉搜索树中寻找最低共同父节点
很简单的题目,直接贴代码
/**
* 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 == NULL){
return root;
}
int min = p->val > q->val ? q->val : p->val;
int max = p->val > q->val ? p->val : q->val;
if (root->val >= min && root->val <= max) {
return root;
}
if (root->val < min) {
return lowestCommonAncestor(root->right, p, q);
}
if (root->val > max) {
return lowestCommonAncestor(root->left, p, q);
}
}
};