/
ctciisbinarysearchtree_23952.java
59 lines (50 loc) · 1.79 KB
/
ctciisbinarysearchtree_23952.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*****************************
Code by: David Zentner dazcode@gmail.com
http://www.dazcode.com/
this code is an accepted solution for code challenge located at:
https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
this code may need to run in the hackerrank online ide to work correctly
*****************************/
/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.
The Node class is defined as follows:
class Node {
int data;
Node left;
Node right;
}
boolean checkBST(Node root) {
int currentData=root.data;
printvalue("root:"+currentData);
if(root.left!=null){
printvalue("root:"+currentData+",left:"+root.left.data);
if(!(root.left.data<currentData)){
return false;
}
if (!checkBST(root.left)){
return false;
}
}
if(root.right!=null){
printvalue("root:"+currentData+",left:"+root.right.data);
if(!(root.right.data>currentData)){
return false;
}
if (!checkBST(root.right)){
return false;
}
}
return true;
}
static void printvalue(String theValue){
//System.out.println(theValue);
}
*/
boolean checkBST(Node root) {
return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
boolean checkBST(Node node, int min, int max) {
if (node == null) return true;
return min < node.data && node.data < max &&
checkBST(node.left, min, node.data) &&
checkBST(node.right, node.data, max);
}