-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_1991.java
105 lines (91 loc) · 2.67 KB
/
number_1991.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
import java.util.Scanner;
public class number_1991 {
static class node{
char data;
node left; node right;
node(char data){
this.data = data;
}
}
static class tree{
node root;
void add_tree(char data, char left, char right){
if(root == null){
if(data != '.'){
root = new node(data);
}
if(left != '.'){
root.left = new node(left);
}
if(right != '.'){
root.right = new node(right);
}
}
else{
search_tree(root, data, left, right);
}
}
void search_tree(node root,char data, char left, char right){
if(root == null){
return;
}
else if(root.data == data){
if(left != '.'){
root.left = new node(left);
}
if(right != '.'){
root.right = new node(right);
}
}
else{
search_tree(root.left, data, left, right);
search_tree(root.right, data, left, right);
}
}
void preorder(node root){
System.out.print(root.data);
if(root.left != null){
preorder(root.left);
}
if(root.right != null){
preorder(root.right);
}
}
void inorder(node root){
if(root.left != null){
inorder(root.left);
}
System.out.print(root.data);
if(root.right != null){
inorder(root.right);
}
}
void postorder(node root){
if(root.left != null){
postorder(root.left);
}
if(root.right != null){
postorder(root.right);
}
System.out.print(root.data);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
tree Tree = new tree();
for(int i=0;i<n;i++){
String tmp[] = sc.nextLine().split(" ");
char root = tmp[0].charAt(0);
char left = tmp[1].charAt(0);
char right = tmp[2].charAt(0);
Tree.add_tree(root, left, right);
}sc.close();
Tree.preorder(Tree.root);
System.out.println();
Tree.inorder(Tree.root);
System.out.println();
Tree.postorder(Tree.root);
}
}