I'm creating a binary tree and I'm stuck to convert it to postfix and infix. The problem is that I'm trying to create a method infix
and postfix
inside the class but it doesn’t work:
TypeError: Node.Postfix() takes 1 positional argument but 2 were given
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def Postfix(self):
if Node:
self.Postfix(self.left)
self.Postfix(self.right)
print(Node.val, end=" ")
X="- + a b * * e f g"
r=Node.constructTree(X)
r.Postfix()
I'm building my tree using the stack.
The main problem is that you use Postfix
method with an argument, but it doesn't accept one.
In Python the methods are like functions, but their first argument (self
) is an object. So, to call the Postfix
method on the left subtree use should use self.left.Postfix()
.
Another problem is that before calling Postfix
you should test if the subtree exists. And you should use self.val
instead of Node.val
to get a value of the node.
If you fix all these errors you get something like this:
def Postfix(self):
if self.left:
self.left.Postfix()
if self.right:
self.right.Postfix()
print(self.val, end=" ")