求俩个节点的最低公共祖先

本题源自leetcode  235

—————————————————————-

递归:

代码:

 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root)
            return NULL;
        if(p && q && p->val < root->val && q->val < root->val)
            return lowestCommonAncestor(root->left,p,q);
        if(p && q && p->val > root->val && q->val > root->val)
            return lowestCommonAncestor(root->right,p,q);
        return root;
    }

代码 非递归

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root)
            return NULL;
        TreeNode* cur = root;
        while(cur){
            if(p->val < cur->val && q->val < cur->val)
                cur = cur->left;
            else if(p->val > cur->val && q->val > cur->val)
                cur = cur->right;
            else
                return cur;
        }
       return cur;
    }
点赞