Accepted C++ O(H) solution 36ms


  • 0
    J
    class Solution {
    public:
        TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
            if(p->right){
                TreeNode *tmp=p->right;
                while(tmp->left)tmp=tmp->left;
                return tmp;
            }
            TreeNode *prev=root;
            TreeNode *post=NULL;
            while(prev && prev->val!=p->val){
                if(prev->val>p->val)post=prev;
                prev=prev->val>p->val?prev->left:prev->right;
            }
            return post;
        }
    };

  • 0
    This post is deleted!

Log in to reply
 

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