-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBInaryTree.java
92 lines (75 loc) · 2.45 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
import java.util.Scanner;
public class BInaryTree {
public BInaryTree (){
}
private static class Node{
int value ;
Node left ;
Node right ;
public Node (int value){
this.value= value ;
}
}
private Node root;
public void populate (Scanner scanner){
System.out.println("Enter a root node value :-");
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 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 right of " + node.value);
int value = scanner.nextInt();
node.right = new Node(value);
populate(scanner, node.right );
}
}
public void display(){
display(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 betterDisplay (){
betterDisplay(root , 0);
}
private void betterDisplay (Node node , int leval){
if (node == null){
return ;
}
betterDisplay(node.right, leval+1);
if (leval != 0 ){
for (int i = 0; i < leval -1; i++) {
System.out.print("|\t\t");
}
System.out.println("|-------->" + node.value);
}
else {
System.out.println(node.value);
}
betterDisplay(node.left, leval+1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BInaryTree tree = new BInaryTree() ;
tree.populate(scanner);
tree.display();
tree.betterDisplay();
}
}