-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
83 lines (71 loc) · 1.55 KB
/
BinarySearchTree.java
File metadata and controls
83 lines (71 loc) · 1.55 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
73
74
75
76
77
78
79
80
81
82
83
package technical;
public class BinarySearchTree {
private Treenode root;
public class Treenode {
private Treenode left;
private Treenode right;
private int data;
public Treenode(int data) {
this.data = data;
}
}
public void insert(int value) {
root = insert(root, value);
}
public Treenode insert(Treenode root, int data) {
if (root == null) {
root = new Treenode(data);
return root;
}
if (data < root.data) {
root.left = insert(root.left, data);
} else {
root.right = insert(root.right, data);
}
return root;
}
public void inorder() {
inorder(root);
}
public boolean isValid(Treenode root,long min,long max) {
if(root==null) {
return true;
}
if(root.data<=min ||root.data>=max) {
return false;
}
boolean left=isValid(root.left,min,root.data);
if(left) {
boolean right=isValid(root.right,root.data,max);
return true;
}
return false;
}
public void inorder(Treenode root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public Treenode search(Treenode root,int key) {
if(root==null || root.data==key) {
return root;
}
if(key<root.data) {
return search(root.left,key);
}else{
return search(root.right,key);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(3);
bst.insert(1);
bst.insert(6);
bst.insert(5);
bst.insert(7);
bst.inorder();
}
}