C++, Iterative, O(h) time


  • 0
    C
    class Solution {
    public:
        TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
            if (!root || !p) return 0;
    
            TreeNode *curr = root, *succ;
            while (curr)
            {
                if (curr->val == p->val)
                    curr = curr->right;
                else if (curr->val > p->val)
                {
                    succ = curr;
                    curr = curr->left;
                }
                else
                    curr = curr->right;
            }
            return succ;
        }
    };

Log in to reply
 

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