-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.java
More file actions
71 lines (59 loc) · 1.54 KB
/
Copy pathBST.java
File metadata and controls
71 lines (59 loc) · 1.54 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
package Algorithms;
import java.util.Scanner;
import java.util.*;
/* 4 2 1 -1 -1 3 -1 -1 5 -1 6 -1 -1 */
public class BST{
static Scanner input = null;
public static void main(String[] args) {
try{
input = new Scanner(System.in);
NodeMy root = BST();
System.out.print("Key :");
int key = input.nextInt();
boolean x = BS(root, key);
System.out.println(x);
inorder(root);}
catch(Exception e){
System.out.println("Catch");
}
}
static NodeMy BST() {
NodeMy newnode = null;
int val = input.nextInt();
if (val == -1) {
return null;
}
newnode = new NodeMy(val);
newnode.left = BST();
newnode.right = BST();
return newnode;
}
public static boolean BS(NodeMy root, int key) {
if (root == null) {
return false;
} else if (root.val > key) {
return BS(root.left, key);
} else if (root.val < key) {
return BS(root.right, key);
} else if (root.val == key) {
return true;
}
return false;
}
static void inorder(NodeMy root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.val + " ");
inorder(root.right);
}
}
class NodeMy {
int val;
NodeMy left;
NodeMy right;
public NodeMy(int val) {
this.val = val;
}
}