Tree: Inorder Traversal

  • + 0 comments

    class Node: def init(self, val): self.value = val self.right = None self.left = None

    class Tree: def init(self): self.root = None

    def insert(self, root, val):
        if root is None:
            return Node(val)
        elif val < root.value:
            if root.left is None:
                root.left = Node(val)
            else:
                self.insert(root.left, val)
        else:
            if root.right is None:
                root.right = Node(val)
            else:
                self.insert(root.right, val)
        return root
    
    def inorder(self, root):
        if root is None:
            return 
        self.inorder(root.left)
        print(root.value, end=' ')
        self.inorder(root.right)
    

    n=int(input()) numbers = list(map(int,input().split()))

    Initialize the tree and create root

    tree = Tree() tree.root = Node(numbers[0])

    Insert remaining numbers

    for number in numbers[1:]: tree.insert(tree.root, number)

    Perform in-order traversal

    tree.inorder(tree.root)