C solution (22ms) - Iterative approach


  • 0
    struct TreeNode* lowestCommonAncestor(struct TreeNode* node, struct TreeNode* lo, struct TreeNode* hi) {
        struct TreeNode *tmp;
        if (!node || !lo || !hi) { return NULL; }
        // Make sure 'lo' is always the lesser valued node
        if (lo->val > hi->val) { tmp = lo; lo = hi; hi = tmp;}
        while (node) {
            if (lo->val > node->val) {
                node = node->right;
            } else if (hi->val < node->val) {
                node = node->left;
            } else {
                // lo->val < node->val && node->val < hi->val
                // OR lo->val == node->val
                // OR hi->val == node->val
                return node;
            }
        }
        return NULL;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.