-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
67 lines (57 loc) · 1.57 KB
/
BinarySearchTree.java
File metadata and controls
67 lines (57 loc) · 1.57 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
package devSet;
import java.util.ArrayList;
public class BinarySearchTree {
private TreeNode root = new TreeNode();
private int size = 0;
public TreeNode insertKey(TreeNode root, int x) {
TreeNode p = root;
TreeNode newNode = new TreeNode(x);
this.size++;
if(p==null){
this.size--;
return newNode;
}
else if(p.data>newNode.data){
p.left = insertKey(p.left, x);
return p;
}
else if(p.data<newNode.data){
p.right = insertKey(p.right, x);
return p;
}
else{
return p;
}
}
public int getSize() {
return this.size;
}
public void insertBST(int x){
root = insertKey(root, x);
}
public TreeNode searchBST(int x){
TreeNode p = root;
while(p!=null){
if(x<p.data) p = p.left;
else if(x>p.data) p = p.right;
else return p;
}
return p;
}
public void inorder(TreeNode root, ArrayList<Integer> arr){
if(this.root!=null){
inorder(root.left, arr);
arr.add(root.data);
inorder(root.right, arr);
}
}
public int[] inorder() {
int[] result = new int[this.size];
ArrayList<Integer> list = new ArrayList<Integer>();
this.inorder(this.root, list);
for(int i=0; i<list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}