-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckBST.java
39 lines (33 loc) · 884 Bytes
/
CheckBST.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
package ctci;
//https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
public class CheckBST {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// accepted
boolean checkBST(Node1 root) {
return helperBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
boolean helperBST(Node1 root, int min, int max) {
if (root == null)
return true;
if (root.data <= min || root.data >= max)
return false;
return (helperBST(root.left, min, root.data) && helperBST(root.right, root.data, max));
}
//failed
boolean checkBST1(Node1 root) {
if (root == null)
return true;
if (root.left != null && root.left.data > root.data)
return false;
if (root.right != null && root.right.data < root.data)
return false;
return checkBST(root.left) && checkBST(root.right);
}
}
class Node1 {
int data;
Node1 left;
Node1 right;
}