-
Notifications
You must be signed in to change notification settings - Fork 10
/
Tree from Bracket Representation
71 lines (65 loc) · 1.84 KB
/
Tree from Bracket Representation
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
import java.util.*;
class Node{
int data;
Node left;
Node right;
}
class tree{
Node root;
void preorder(Node n){
System.out.print(n.data+" ");
if(n.left!=null){
preorder(n.left);
}
if(n.right!=null){
preorder(n.right);
}
}
void divide(String data,Node n){
n.data=Integer.parseInt(String.valueOf(data.charAt(0)));
if(data.length()==1){
return;
}
Stack<Character>s=new Stack<>();
s.push(data.charAt(1));
int count=2;
String s1="";
String s2="";
while(!s.isEmpty()){
if(data.charAt(count)!=')') {
s1 = s1 + data.charAt(count);
}
if(data.charAt(count)=='('){
s.push(data.charAt(count));
}
if(data.charAt(count)==')'){
s.pop();
if(!s.isEmpty()){
s1=s1+")";
}
}
count++;
}
for(int i=count+1;i<data.length()-1;i++){
s2=s2+data.charAt(i);
}
// System.out.println(s1);
// System.out.println(s2);
if(!s1.equals("")){
n.left=new Node();
divide(s1,n.left);
}
if(!s2.equals("")){
n.right=new Node();
divide(s2,n.right);
}
}
}
public class Implementation {
public static void main(String []args){
tree t=new tree();
t.root=new Node();
t.divide("4(2(3)(1))(6(5))",t.root);
t.preorder(t.root);
}
}