The first thought of recursion, but did not expect to use the upper and lower limit method, but added a parent as the parameter, the result is very troublesome. The code is concise and clear after the upper and lower limits are used.
Package Level3; import Utility. treeNode;/*** Validate Binary Search Tree ** Given a binary tree, determine if it is a valid binary search tree (BST ). assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. the right subtree of a node contains only nodes with keys greater than the node's key. both the left and right subtrees must also Be binary search trees. confused what "{1, #, 2, 3}" means?> Read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below. here's an example: 1/\ 2 3/4 \ 5 The above binary tree is serialized as "{, 3, #,#, 4, #,#, 5 }". **/public class S98 {public static void main (String [] args) {TreeNode root = new TreeNode (3); TreeNode p1 = new TreeNode (1 ); treeNode p2 = new TreeNode (5); TreeNode p3 = new TreeNode (0); TreeNode p4 = new TreeNode (2); TreeNode p5 = new TreeNode (4 ); treeNode p6 = new TreeNode (6); root. left = p1; root. right = p2; p1.left = p3; p1.right = p4; p2.left = p5; p2.right = p6; System. out. println (isValidBST (root);} public static boolean isValidBST (TreeNode root) {return rec (root, Integer. MIN_VALUE, Integer. MAX_VALUE);} // use the minimum and maximum values to specify the subtree range public static boolean rec (TreeNode root, int min, int max) {if (root = null) {return true;} // if (root. val <= min | root. val> = max) {return false;} // check the legality of the left and right subtree and update the upper and lower limits of return rec (root. left, min, root. val) & rec (root. right, root. val, max );}}