-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarytree.py
194 lines (65 loc) · 2.52 KB
/
binarytree.py
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class binary_tree:
def TREE(self):
data = int(input('data'))
root = node(data)
L = int(input('1 TO LEFT'))
if(L==1):
root.left=self.TREE()
R = int(input('1 TO RIGHT'))
if(R==1):
root.right = self.TREE()
return root
def display(self,root):
if(root!=None):
self.display(root.left)
print(root.data)
self.display(root.right)
object = binary_tree()
root = object.TREE()
object.display(root)
'''class binary_tree:
def __init__(self, infix, postfix):
self.infix = infix
self.postfix = postfix
def tree(self):
# Create a dictionary to store the index of each element in the infix expression
index_map = {char: i for i, char in enumerate(self.infix)}
# Define a recursive function to construct the binary tree
def construct_tree(postfix, start, end):
if start > end:
return None
# Get the current node's value from the postfix expression
node_value = postfix.pop()
# Create a new node
current_node = node(node_value)
# If the node is an operator, recursively construct its left and right subtrees
if node_value in '+-*/':
# Get the index of the current node in the infix expression
index = index_map[node_value]
# Recursively construct the right subtree
current_node.right = construct_tree(postfix, index + 1, end)
# Recursively construct the left subtree
current_node.left = construct_tree(postfix, start, index - 1)
return current_node
# Convert the postfix expression to a list for easier manipulation
postfix_list = list(self.postfix)
# Construct the binary tree
root = construct_tree(postfix_list, 0, len(self.infix) - 1)
return root
def print_tree(self, root, level=0):
if root is not None:
self.print_tree(root.right, level + 1)
print(' ' * 4 * level + '->', root.data)
self.print_tree(root.left, level + 1)
# Example usage:
infix = "A+B*C"
postfix = "ABC*+"
tree = binary_tree(infix, postfix)
root = tree.tree()
tree.print_tree(root)
'''