-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathinorder-traversal-example.py
55 lines (41 loc) · 1.41 KB
/
inorder-traversal-example.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
from stack import Stack
import operator
import re
from treenode import TreeNode
opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
pattern = re.compile("[0-9]")
string = "( ( 10 + 5 ) * 3 )"
def tree_parser(s: str) -> TreeNode:
arr: list = s.split()
stack: Stack = Stack()
node: TreeNode = TreeNode()
current_node: TreeNode = node
stack.push(node)
for e in arr:
if e == "(":
current_node.insert_left()
stack.push(current_node)
current_node = current_node.get_left_child()
elif e in "+-*/":
current_node.insert_root_value(e)
current_node.insert_right()
stack.push(current_node)
current_node = current_node.get_right_child()
elif pattern.match(e):
current_node.insert_root_value(int(e))
current_node = stack.pop()
elif e == ")":
current_node = stack.pop()
else:
raise Exception()
return node
tree_node: TreeNode = tree_parser(string)
def inorder(node: TreeNode) -> str:
ret_value: str = ""
if node.get_left_child() is not None:
ret_value += "(" + inorder(node.get_left_child())
ret_value += str(node.get_root_value())
if node.get_right_child() is not None:
ret_value += inorder(node.get_right_child()) + ")"
return ret_value
print(inorder(tree_node)) # ((10+5)*3)