java simple solution 4ms


  • 0
    K
    // use BST porperty
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            if (root == null || p == null) {
                return null;
            }
            TreeNode cur = root;
            TreeNode smallMax = new TreeNode(Integer.MAX_VALUE);
            while (cur != null) { 
                if (cur.val <= p.val) {
                    cur = cur.right;
                }else {
                    if (cur.val < smallMax.val) {
                        smallMax= cur;
                    }
                    cur  = cur.left;
                }
            }
            return smallMax.val == Integer.MAX_VALUE? null : smallMax;
            
        }
    

Log in to reply
 

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