Java iteration solution


  • 0
    B
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode t=null;
        if(p.right!=null){
            t=p.right;
            while(t.left!=null){ t=t.left;}
            return t;
        }
        while(root!=null){
            if(root.val>p.val){
                t=root;
                root=root.left;
            }else if(root.val<p.val) root=root.right;
            else break;
        }
        return t;
    }

Log in to reply
 

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