Skip to content

Commit 23f532a

Browse files
author
shiv
committed
added ternerary exp to binary tree code
1 parent f08b97b commit 23f532a

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

ip.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
2
2-
2
3-
3
2+
a?b:c
3+
a?b?c:d?e:f:g?h:i

ter_exp_to_bin.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# SHIV's code for converting ternary exp to binary tree
2+
3+
'''
4+
3
5+
a?b:c
6+
a?b?c:d:e
7+
a?b?c:d?e:f:g?h:i
8+
9+
'''
10+
11+
tn = int(input())
12+
13+
class node:
14+
def __init__(self, name):
15+
self.name = name
16+
self.L= None
17+
self.R = None
18+
self.count = 0
19+
20+
def build_tree(tree):
21+
stack = []
22+
for c in tree:
23+
if c == '?': continue
24+
if c == ':':
25+
old_head = stack[-1]
26+
del stack[-1]
27+
stack[-1].count+=1
28+
if stack[-1].count == 1:
29+
stack[-1].L = old_head
30+
elif stack[-1].count == 2:
31+
stack[-1].R = old_head
32+
del stack[-1]
33+
stack[-1].count+=1
34+
while stack[-1].count == 2:
35+
del stack[-1]
36+
stack[-1].count+=1
37+
else:
38+
curr_node = node(c)
39+
stack.append(curr_node)
40+
while stack[-1].count == 2 or stack[-1].count == 0:
41+
del stack[-1]
42+
if not stack: break
43+
stack[-1].count+=1
44+
print([(x.name, x.count) for x in stack])
45+
46+
for i in range(tn):
47+
tree = input()
48+
root = build_tree(tree)
49+
print('----------------')

0 commit comments

Comments
 (0)