题目
题解
- 利用BST的特点进行二叉搜索
代码
/**
* 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)
return root;
if(p->val>q->val)
return lowestCommonAncestor(root,q,p);
while(root){
if(root->val>=p->val&&root->val<=q->val)
return root;
else if(root->val>p->val&&root->val>q->val){
root=root->left;
}
else{
root=root->right;
}
}
return root;
}
};