Tree: Preorder Traversal

  • + 0 comments

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

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

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

    n=int(input()) nums=list(map(int,input().split())) tree=Tree() tree.root=Node(nums[0]) for num in nums[1:]: tree.insert(tree.root,num) tree.preOrder(tree.root)