Code
利用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 == NULL) return NULL;
TreeNode* tmp = root;
while(tmp)
{
if(tmp->val > p->val && tmp->val > q->val){
tmp = tmp->left;
}
else if(tmp->val < p->val && tmp->val < q->val){
tmp = tmp->right;
}else{
break;
}
}
return tmp;
}
};