class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
if(!p) return q;
if(!q) return q;
TreeNode *r = root;
int mini = min(p->val, q->val);
int maxi = max(p->val, q->val);
while(r){
if(mini <= r->val && maxi >= r->val)
return r;
else if(mini > r->val)
r = r->right;
else
r = r->left;
}
return NULL;
}
};
235. Lowest Common Ancestor of a Binary Search Tree
最新推荐文章于 2020-02-26 19:44:50 发布