3. Build a Simple Binary Tree from user input
Simple Binary Tree using Recursion¶
In [1]:
Copied!
from utils.nodes import BinaryTreeNode as Node
from utils.tree_traversal import TreeTraversal as tt
from utils.nodes import BinaryTreeNode as Node
from utils.tree_traversal import TreeTraversal as tt
In [2]:
Copied!
def create():
print("Enter data (-1 for no data): ")
data = int(input())
if data == -1:
return None
node = Node(data)
print(f"Enter left child for: {data}")
node.left = create()
print(f"Enter right child for: {data} ")
node.right = create()
return node
def create():
print("Enter data (-1 for no data): ")
data = int(input())
if data == -1:
return None
node = Node(data)
print(f"Enter left child for: {data}")
node.left = create()
print(f"Enter right child for: {data} ")
node.right = create()
return node
In [7]:
Copied!
root = create()
root = create()
Enter data (-1 for no data): 1 Enter left child for: 1 Enter data (-1 for no data): 2 Enter left child for: 2 Enter data (-1 for no data): 3 Enter left child for: 3 Enter data (-1 for no data): -1 Enter right child for: 3 Enter data (-1 for no data): -1 Enter right child for: 2 Enter data (-1 for no data): 4 Enter left child for: 4 Enter data (-1 for no data): 5 Enter left child for: 5 Enter data (-1 for no data): -1 Enter right child for: 5 Enter data (-1 for no data): -1 Enter right child for: 4 Enter data (-1 for no data): -1 Enter right child for: 1 Enter data (-1 for no data): 6 Enter left child for: 6 Enter data (-1 for no data): 7 Enter left child for: 7 Enter data (-1 for no data): -1 Enter right child for: 7 Enter data (-1 for no data): -1 Enter right child for: 6 Enter data (-1 for no data): 8 Enter left child for: 8 Enter data (-1 for no data): -1 Enter right child for: 8 Enter data (-1 for no data): -1
In [11]:
Copied!
tt.traverse_preorder(root)
tt.traverse_preorder(root)
1 2 3 4 5 6 7 8
In [12]:
Copied!
tt.traverse_postorder(root)
tt.traverse_postorder(root)
3 5 4 2 7 8 6 1
In [13]:
Copied!
tt.traverse_inorder(root)
tt.traverse_inorder(root)
3 2 5 4 1 7 6 8
In [ ]:
Copied!