forked from starkblaze01/Algorithms-Cheatsheet-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreOrderBST.java
More file actions
59 lines (50 loc) · 958 Bytes
/
preOrderBST.java
File metadata and controls
59 lines (50 loc) · 958 Bytes
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
import java.util.*;
class Node{
int data;
Node left = null;
Node right = null;
public Node(int data){
this.data = data;
}
}
class BST{
Node root;
public BST(Node root){
this.root = root;
}
public Node insert(Node root, Node key){
if (root == null){
root = key;
}
else if (key.data < root.data){
root.left = insert(root.left, key);
}
else{
root.right = insert(root.right, key);
}
return root;
}
void preOrder(Node root){
if (root != null) {
System.out.print(root.data + " ");
}
if (root.left != null) {
preOrder(root.left);
}
if (root.right != null) {
preOrder(root.right);
}
return;
}
}
public class preOrderBST {
public static void main(String[] args){
int[] arr = new int[]{7,1,2,3,4,5,6,8,9};
Node root = new Node(arr[0]);
BST tree = new BST(root);
for (int i = 1; i < arr.length; i++){
tree.root = tree.insert(root,new Node(arr[i]));
}
tree.preOrder(tree.root);
}
}