-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathbinaryTree.java
88 lines (70 loc) Β· 1.77 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
package Lecture20;
import java.util.Scanner;
public class binaryTree {
private class Node {
int data;
Node left;
Node right;
Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
private Node root;
private int size = 0;
public binaryTree() {
Scanner sc = new Scanner(System.in);
this.root = takeTreeInput(sc, null, false);
}
private Node takeTreeInput(Scanner sc, Node parent, boolean isLeftorRight) {
if (parent == null) {
System.out.print("Enter data for root node: ");
} else {
if (isLeftorRight) {
System.out.print("Enter data for left child of " + parent.data + ": ");
} else {
System.out.print("Enter data for right child of: " + parent.data + ": ");
}
}
int data = sc.nextInt();
Node node = new Node(data, null, null);
this.size++;
boolean choice = false;
System.out.print("Do you have left child for " + node.data + " -> true/false: ");
choice = sc.nextBoolean();
if (choice) {
node.left = this.takeTreeInput(sc, node, true);
}
choice = false;
System.out.print("Do you have right child for " + node.data + " -> true/false: ");
choice = sc.nextBoolean();
if (choice) {
node.right = this.takeTreeInput(sc, node, false);
}
return node;
}
public void display() {
this.display(this.root);
}
private void display(Node node) {
if (node.left != null) {
System.out.print(node.left.data + " => ");
} else {
System.out.print("END => ");
}
System.out.print(node.data);
if (node.right != null) {
System.out.print(" <= " + node.right.data);
} else {
System.out.print(" <= END");
}
System.out.println();
if (node.left != null) {
this.display(node.left);
}
if (node.right != null) {
this.display(node.right);
}
}
}