Concise Java solution


  • 0
    J

    The key is the two bound, lo and hi, that help check whether this tree satisfies the property of BST.

    public class Solution {
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, null, null);
        }
    
        private boolean isValidBST(TreeNode node, TreeNode lo, TreeNode hi) {
            if(node == null)
                return true;
            if((lo!=null && node.val<=lo.val) || (hi!=null && node.val>=hi.val))
                return false;        
            return isValidBST(node.left, lo, node) && isValidBST(node.right, node, hi);
        }
    }

Log in to reply
 

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