Hi,
I am trying to build a decision tree from the prefix. The prefix is given in a string, I am reading it by identifying operators and operands from it. No issues here.
My trouble is with actually building the tree, but not using a stack.
Here is my code for adding nodes to the tree:
The code above is actually building 3 as a the right side of the 2 node, instead of both being the left & right of the "*" node.
So smth like this:
Any idea how to solve this?
Many thanks!
Cristina
I am trying to build a decision tree from the prefix. The prefix is given in a string, I am reading it by identifying operators and operands from it. No issues here.
My trouble is with actually building the tree, but not using a stack.
Here is my code for adding nodes to the tree:
def add(self, value): if self.root is None: self.root = BinaryTreeNode(value) else: ptr = self.root while True: if ptr.value in ["+", "-", "*", "/", "%", "//", "**"]: if ptr.left is None: ptr.left = BinaryTreeNode(value) break else: ptr = ptr.left else: if ptr.right is None: ptr.right = BinaryTreeNode(value) break else: ptr = ptr.rightThe problem is it is not moving on the right branch of the tree. Example: "+ * 2 3 - 20 / 15 3"
The code above is actually building 3 as a the right side of the 2 node, instead of both being the left & right of the "*" node.
So smth like this:
Output: +
*
2
3
instead of:Output: +
*
2 3
So the error is that the code doesn't move back up on the branch of the tree. Any idea how to solve this?
Many thanks!
Cristina
Larz60+ write Oct-21-2020, 11:01 AM:
Please post code within code tags, I added them for you this time.
Please post code within code tags, I added them for you this time.