File tree 1 file changed +35
-0
lines changed
Lintcode/src/chapter3_binary_tree_and_divide_and_conquer
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ package chapter3_binary_tree_and_divide_and_conquer ;
2
+
3
+ import classes .TreeNode ;
4
+
5
+ public class ValidateBinarySearchTree {
6
+
7
+
8
+ /**
9
+ * @param root: The root of binary tree.
10
+ * @return: True if the binary tree is BST, or false
11
+ */
12
+ public static boolean isValidBST (TreeNode root ) {
13
+ if (root == null ) return true ;
14
+ return dfs (root , Long .MIN_VALUE , Long .MAX_VALUE );
15
+ }
16
+
17
+ static boolean dfs (TreeNode root , long min , long max ){
18
+ if (root == null ) return true ;
19
+ if ( (long ) root .val >= max || (long ) root .val <= min ) return false ;
20
+ boolean left = dfs (root .left , min , root .val );
21
+ boolean right = true ;
22
+ if (left ) right = dfs (root .right , root .val , max );
23
+ return left && right ;
24
+ }
25
+
26
+
27
+
28
+ public static void main (String ...strings ){
29
+ TreeNode root = new TreeNode (2 );
30
+ root .left = new TreeNode (1 );
31
+ root .right = new TreeNode (2 );
32
+ System .out .println (isValidBST (root ));
33
+ }
34
+
35
+ }
You can’t perform that action at this time.
0 commit comments