-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST_p3.java
More file actions
72 lines (65 loc) · 1.36 KB
/
BST_p3.java
File metadata and controls
72 lines (65 loc) · 1.36 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
//Count BST subtrees that lie in given range
class Node{
int val;
Node left;
Node right;
Node(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
public class BST_p3{
static int count;
static boolean countbst(Node root, int low, int high){
if(root != null){
boolean rt = (root.val >= low && root.val <= high)?true:false;
if(root.left != null && root.right != null){
boolean l = countbst(root.left, low, high);
boolean r = countbst(root.right, low, high);
if(rt && l && r){
count++;
return true;
}
return false;
}
else if(root.left == null && root.right != null){
boolean r = countbst(root.right, low, high);
if(rt && r){
count++;
return true;
}
return false;
}
else if(root.left != null && root.right == null){
boolean l = countbst(root.left, low, high);
if(rt && l){
count++;
return true;
}
return false;
}
else{
if(rt){
count++;
return true;
}
return false;
}
}
return false;
}
public static void main(String[] args){
Node root = new Node(10);
root.left = new Node(5);
root.left.left = new Node(1);
root.right = new Node(50);
root.right.left = new Node(40);
root.right.right = new Node(100);
int low = 1;
int high = 45;
count = 0;
countbst(root, low, high);
System.out.println(count);
}
}