Java 5ms short code using recursion


  • 0
    S

    public class Solution {

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    
        if (p == null || root == null) {
            return null;
        }
        
        TreeNode inorderSuccessor = null;
        if (root.val <= p.val){
            inorderSuccessor = inorderSuccessor(root.right, p);
        } else {
            inorderSuccessor = inorderSuccessor(root.left, p);
        }
        
        return (inorderSuccessor == null && root.val > p.val) ? root : inorderSuccessor;
    }
    

    }


Log in to reply
 

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