235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:位面淘宝txt 编辑:程序博客网 时间:2024/06/01 23:00

这里写图片描述

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(!root) return NULL;        if(root->val>max(p->val,q->val))            return lowestCommonAncestor(root->left,p,q);        else if(root->val<min(p->val,q->val))            return lowestCommonAncestor(root->right,p,q);        else return root;    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(!root) return NULL;        while(true){            if(root->val>max(p->val,q->val))                root=root->left;            else if(root->val<min(p->val,q->val))                root=root->right;            else break;        }        return root;    }
阅读全文
0 0