1+ from tree import TreeNode
2+ from stack import Stack
3+
4+ import operator
5+
6+ opers = {'+' :operator .add , '-' :operator .sub , '*' :operator .mul , '/' :operator .truediv }
7+
8+ import re
9+ pattern = re .compile ("[0-9]" )
10+
11+ string = "( ( 10 + 5 ) * 3 )"
12+
13+ def treeParser (string : str )-> TreeNode :
14+ string = string .split ()
15+ tree = TreeNode ()
16+ stack : Stack = Stack ()
17+ currentTree : TreeNode = tree
18+ stack .push (tree )
19+ for item in string :
20+ if item == "(" :
21+ currentTree .insertLeft ()
22+ stack .push (currentTree )
23+ currentTree = currentTree .getLeftChild ()
24+ elif item == ")" :
25+ currentTree = stack .pop ()
26+ elif item in "+-*/" :
27+ currentTree .setRootValue (item )
28+ currentTree .insertRight ()
29+ stack .push (currentTree )
30+ currentTree = currentTree .getRightChild ()
31+ elif pattern .match (item ):
32+ currentTree .setRootValue (int (item ))
33+ currentTree = stack .pop ()
34+ else :
35+ raise ValueError ()
36+
37+ return tree
38+
39+ tree : TreeNode = treeParser (string )
40+
41+ def prettyPrint (bt : TreeNode , indent : int ):
42+ print (indent * "." , bt .key )
43+ if bt .leftChild is not None :
44+ prettyPrint (bt .leftChild , indent + 2 )
45+ if bt .rightChild is not None :
46+ prettyPrint (bt .rightChild , indent + 2 )
47+
48+ prettyPrint (bt , 0 )
0 commit comments