-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
63 lines (60 loc) · 1.2 KB
/
BinaryTree.java
File metadata and controls
63 lines (60 loc) · 1.2 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
import java.util.*;
// Binary Tree implementation using array.
class Tree {
int size;
int ar[] ;
Tree(int size) {
this.size = size;
ar = new int[size];
}
void setRoot(int data) {
ar[0] = data;
}
void setLeft(int data, int parent) {
if(ar[parent] == 0) {
System.out.println("Invalid");
return;
}
int child = 2*parent + 1;
if(child < 10) {
ar[child] = data;
return;
}
System.out.println("Overflow");
}
void setRight(int data, int parent) {
if(ar[parent] == 0) {
System.out.println("Invalid");
return;
}
int child = 2*parent + 2;
if(child < 10) {
ar[child] = data;
return;
}
System.out.println("Overflow");
}
public void printTree(int size){
for (int i = 0; i < size; i++) {
if (ar[i] != 0)
System.out.print(ar[i]+" ");
else
System.out.print("_"+" ");
}
}
}
class BinaryTree {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
System.out.println("Enter the size: ");
int size = Sc.nextInt();
Tree T = new Tree(size);
T.setRoot(1);
T.setLeft(2,0);
T.setRight(5,0);
T.setLeft(20,1);
T.setRight(10,1);
T.setLeft(23,3);
T.printTree(size);
}
}