C++ O(h) solution in one pass


  • 25
    S
    class Solution {
    public:
        TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
            if (root == NULL || p == NULL) return NULL;
            
            TreeNode *suc = NULL;
            while (root != NULL) {
                if (root->val <= p->val) {
                    root = root->right;
                } else {
                    suc = root;
                    root = root->left;
                }
            }
            
            return suc;
        }
    };

  • 0
    N

    This solution is not complete. It will return some node in the tree if p doesn't exist in the tree. Should have returned NULL or error code.


Log in to reply
 

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