Can someone explain this recursive Java code?


  • 0
    P
    Integer pred = null;
    public boolean isValidBST(TreeNode root) { 
            if (root == null) return true;
            if (!isValidBST(root.left)) return false;
            // visit
            if (pred != null && root.val <= pred) return false; // I don't quite understand what this line means
            
            pred = root.val; // set
            if (!isValidBST(root.right)) return false;
            return true;
    }
    

    please help to explain this if (pred != null && root.val <= pred) return false;


  • 0
    N

    It means if pred is not null or if pred's value greater than the present nodes value it will return false.
    Remember in inorder traversal of binary search tree the values must be in increasing order...
    Here the basically code checks that condition and then updates the last value seen and so on...


Log in to reply
 

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