-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
119 lines (99 loc) · 2.5 KB
/
BinaryTree.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.util.Scanner;
class BinaryTree {
private static class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
private Node root;
// insert elements
public void populate(Scanner scanner) {
System.out.println("Enter the root Node: ");
int value = scanner.nextInt();
root = new Node(value);
populate(scanner, root);
}
private void populate(Scanner scanner, Node node) {
System.out.println("Do you want to enter left of " + node.value);
boolean left = scanner.nextBoolean();
if (left) {
System.out.println("Enter the value of the left of " + node.value);
int value = scanner.nextInt();
node.left = new Node(value);
populate(scanner, node.left);
}
System.out.println("Do you want to enter right of " + node.value);
boolean right = scanner.nextBoolean();
if (right) {
System.out.println("Enter the value of the right of " + node.value);
int value = scanner.nextInt();
node.right = new Node(value);
populate(scanner, node.right);
}
}
public void display() {
display(this.root, "");
}
private void display(Node node, String indent) {
if (node == null) {
return;
}
System.out.println(indent + node.value);
display(node.left, indent + "\t");
display(node.right, indent + "\t");
}
public void prettyDisplay() {
prettyDisplay(root, 0);
}
private void prettyDisplay(Node node, int level) {
if (node == null) {
return;
}
prettyDisplay(node.right, level + 1);
if (level != 0) {
for (int i = 0; i < level - 1; i++) {
System.out.print("|\t\t");
}
System.out.println("|------->" + node.value);
} else {
System.out.println(node.value);
}
prettyDisplay(node.left, level + 1);
}
public void preOrder() {
preOrder(root);
}
private void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.value + " ");
preOrder(node.left);
preOrder(node.right);
}
public void inOrder() {
preOrder(root);
}
private void inOrder(Node node) {
if (node == null) {
return;
}
preOrder(node.left);
System.out.print(node.value + " ");
preOrder(node.right);
}
public void postOrder() {
preOrder(root);
}
private void postOrder(Node node) {
if (node == null) {
return;
}
preOrder(node.left);
preOrder(node.right);
System.out.print(node.value + " ");
}
}