GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Inorder traversal in python - Couldn't remove the error. Need help

I am very new to Python, I am trying to implement inorder tree traversal. Kindly help me to rectify the code, if possible. Thanks.

class Node :
    left = None
    right = None
    data = None

def new_node(data):
    x = Node()
    x.left = None
    x.right = None
    x.data = data
    return x

def inorder(root):
    if(root == None):
        return
    
    inorder(root.left)
    print (root.data + " ")
    inorder(root.right)

def insert(root, key): 
    if(root == None) :
        return new_node(key)
    
    if(root.data < key) :
        root.right = insert(root.right, key)
    else : root.left = insert(root.left, key)
    
    return root

troot = new_node(0)
n = None
print ("Enter the number of nodes in the tree: ")
n = int(input())

for i in range(n):
    troot = insert(troot, int(input())

inorder(troot)
exit()
asked Jan 18, 2016 by Rahul

1 Answer

 

class Node():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def __str__(self):
        return self.data

    def inorder(self, node):
        if node is not None:
            self.inorder(node.left)
            print(node.data)
            self.inorder(node.right)

    def preorder(self, node):
        if node is not None:
            print(node.data)
            self.preorder(node.left)
            self.preorder(node.right)

    def size(self, node):
        if node is None:
            return 0
        return self.size(node.left) + 1 + self.size(node.right)


tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.inorder(tree)
print(tree.size(tree))

 

answered Jan 19, 2016 by akkii00744
...