Last active
December 15, 2019 20:43
-
-
Save Sukhrobjon/96b7bd019f94d7236dea38ae4deadf2a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def insert(self, expression: str): | |
| """ | |
| Insert the postfix expression into the tree using stack | |
| """ | |
| postfix_exp = self.infix_to_postfix(expression) | |
| # if max size is 0, then it is infinite | |
| stack = deque() | |
| char = postfix_exp[0] | |
| # create a node for the first element of the expression | |
| node = BinaryTreeNode(char) | |
| # push it to stack | |
| stack.appendleft(node) | |
| # iterator for expression | |
| i = 1 | |
| while len(stack) != 0: | |
| char = postfix_exp[i] | |
| # if char is float or int | |
| if '.' in char or char.isdigit(): | |
| # create a node and push the node into the stack | |
| node = BinaryTreeNode(char) | |
| stack.appendleft(node) | |
| else: | |
| # create a parent(operator) node for operands | |
| operator_node = BinaryTreeNode(char) | |
| operator_node.operator = True | |
| # pop the last pushed item and create right_child | |
| right_child = stack.popleft() | |
| # pop item one before the last item and create left_child | |
| left_child = stack.popleft() | |
| # assign those as a child of the (parent)operator | |
| operator_node.right = right_child | |
| operator_node.left = left_child | |
| # push back the operator node(subtree) to the stack | |
| stack.appendleft(operator_node) | |
| # check if we reach last element in the expression | |
| # so we can define the root of the tree | |
| if len(stack) == 1 and i == len(postfix_exp) - 1: | |
| self.root = stack.popleft() | |
| # increment i | |
| i += 1 | |
| self.size += 1 | |
| print(f"i is {i} in insert ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment