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 is binary search trees.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public BooleanIsvalidbst (TreeNode root) {//[2147483647]//note that because the Val of root is of type int, it may be the maximum or minimum value, so the first setting is the largest or smallest to use long, note the type of the function parameter//the subject is very ingenious. Use the maximum and minimum values to limit the extent of the root node. The most critical is the correct definition of IsValid, which represents whether the value of root is between Min and Max//Another solution is to traverse the two-tree sequence and then detect if it is an incrementing array returnIsValid (Root, (Long) Integer.min_value-1, (Long) integer.max_value+1); } Public BooleanIsValid (TreeNode root,LongMinLongmax) { if(root==NULL){ return true; } LongVal= (Long) Root.val; if(val>min&&val<max) { returnIsValid (Root.left,min,val) &&IsValid (Root.right,val,max); }Else return false; }}
[Leedcode 98] Validate Binary Search Tree