6. Complete Binary Tree from an array
In [8]:
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 [3]:
Copied!
# array elements are assumed to be already present in level order traversal manner
array = [1, 2, 3, 4, 5, 6]
# array elements are assumed to be already present in level order traversal manner
array = [1, 2, 3, 4, 5, 6]
In [5]:
Copied!
def create_complete_binary_tree(arr, curr_idx, max_nodes):
root = None
if curr_idx < max_nodes:
root = Node(arr[curr_idx])
root.left = create_complete_binary_tree(arr, 2 * curr_idx + 1, max_nodes)
root.right = create_complete_binary_tree(arr, 2 * curr_idx + 2, max_nodes)
return root
def create_complete_binary_tree(arr, curr_idx, max_nodes):
root = None
if curr_idx < max_nodes:
root = Node(arr[curr_idx])
root.left = create_complete_binary_tree(arr, 2 * curr_idx + 1, max_nodes)
root.right = create_complete_binary_tree(arr, 2 * curr_idx + 2, max_nodes)
return root
In [7]:
Copied!
root = create_complete_binary_tree(array, curr_idx=0, max_nodes=len(array))
root = create_complete_binary_tree(array, curr_idx=0, max_nodes=len(array))
In [9]:
Copied!
tt.level_order_traversal_iterative(root)
tt.level_order_traversal_iterative(root)
Out[9]:
[1, 2, 3, 4, 5, 6]
In [ ]:
Copied!