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
最新推荐文章于 2024-02-06 06:38:28 发布
297

被折叠的 条评论
为什么被折叠?



