-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
83 lines (74 loc) · 1.9 KB
/
BinarySearchTree.java
File metadata and controls
83 lines (74 loc) · 1.9 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
public class BinarySearchTree {
public class Node {
Node left;
int data;
Node right;
Node(int data) {
this.data = data;
this.right = null;
this.left = null;
}
}
Node root;
public void addElements(int data) {
Node newNode = new Node(data);
if (root == null) {
root = newNode;
return;
}
Node i = root;
while (true) {
if (i.data > newNode.data) {
if (i.left == null) {
i.left = newNode;
return;
}
i = i.left;
continue;
} else if (i.data <= newNode.data) {
if (i.right == null) {
i.right = newNode;
return;
}
i = i.right;
}
}
}
public void inorder(Node node) {
if (node == null) {
return;
}
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.right);
}
public void postorder(Node node) {
if (node == null) {
return;
}
postorder(node.left);
postorder(node.right);
System.out.print(node.data + " ");
}
public void preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.right);
}
public static void main(String[] args) {
BinarySearchTree BST = new BinarySearchTree();
BST.addElements(3);
BST.addElements(4);
BST.addElements(3);
BST.addElements(1);
BST.addElements(2);
BST.inorder(BST.root);
System.out.println();
BST.postorder(BST.root);
System.out.println();
BST.preorder(BST.root);
}
}