My Java recursive solution


  • 0
    M
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null) return true;
            
            boolean isValid = true;
            
            if(root.left != null) {
                TreeNode leftLargest = getLargest(root.left);
                isValid &= (leftLargest.val < root.val);
            }
            isValid &= isValidBST(root.left);
            
            if(root.right != null) {
                TreeNode rightSmallest = getSmallest(root.right);
                isValid &= (rightSmallest.val > root.val);
            }
            isValid &= isValidBST(root.right);
            
            return isValid;
        }
        
        TreeNode getLargest(TreeNode node){
            if(node==null) return null;
            if(node.right != null) return getLargest(node.right);
            return node;
        }
        
        TreeNode getSmallest(TreeNode node){
            if(node==null) return null;
            if(node.left != null) return getSmallest(node.left);
            return node;
        }
    }

Log in to reply
 

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