Using DFS to traverse the BST, when we look through the BST to a certain node, this node must have the following property to make sure the tree is a valid BST:
if current node is a left child of its parent, its value should smaller than its parent‘s value.
then its left child(if exists,), its value should smaller than its own. While its right child, if exists, the value should should be larger than current node‘s but smaller than the parent‘s
Similarly, we can find the property of a node which is a right child of its parent.
We use two long-type variable to record the MIN, MAX value in the remaining tree. When we goes into a left child of current, update the max to be current node‘s value, when we goes into a right child of current node, update the min to be current node‘s value. Basically the min and max value is related to the parent node‘s value. Initially we set Min to be Integer.MIN_VALUE-1 and MAX to be Integer.MAX_VALUE +1, to make sure it works when we look into root‘s child nodes, here Using long data type to avoid over range of integer value.
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { if(root == null) return true; long min = (long) (Integer.MIN_VALUE)-1; long max = (long) (Integer.MAX_VALUE)+1; return isValidLeftSubtree(root.left, root.val, min) && isValidRightSubtree(root.right, max, root.val); } public boolean isValidLeftSubtree(TreeNode node, long max, long min){ if(node == null) return true; if(node.val >= max || node.val <= min) return false; return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val); } public boolean isValidRightSubtree(TreeNode node, long max, long min){ if(node == null) return true; if(node.val >= max || node.val <= min) return false; return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val); } }