You are viewing a single comment's thread. Return to all 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()))
tree = Tree() tree.root = Node(numbers[0])
for number in numbers[1:]: tree.insert(tree.root, number)
tree.inorder(tree.root)
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Inorder Traversal
You are viewing a single comment's thread. Return to all comments →
class Node: def init(self, val): self.value = val self.right = None self.left = None
class Tree: def init(self): self.root = None
n=int(input()) numbers = list(map(int,input().split()))
Initialize the tree and create roottree = Tree() tree.root = Node(numbers[0])
Insert remaining numbersfor number in numbers[1:]: tree.insert(tree.root, number)
Perform in-order traversal
tree.inorder(tree.root)