0% found this document useful (0 votes)
3 views2 pages

Binary Tree Levelorder Traversal

The document contains Python code for a binary tree implementation, including a TreeNode class and functions for level order traversal. It defines a method to insert nodes into the tree based on an array representation and then retrieves the nodes in level order. The final output prints the level order traversal of the constructed binary tree.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Binary Tree Levelorder Traversal

The document contains Python code for a binary tree implementation, including a TreeNode class and functions for level order traversal. It defines a method to insert nodes into the tree based on an array representation and then retrieves the nodes in level order. The final output prints the level order traversal of the constructed binary tree.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

class TreeNode:

def __init__(self, val=0, left=None, right=None):


self.val = val
self.left = left
self.right = right

def traverse_tree(node, level, levels, max_level):


if node is None:
return max_level

# Store the node value in the corresponding level in the dictionary


if level not in levels:
levels[level] = [node.val]
else:
levels[level].append(node.val)

# Update the maximum level encountered


max_level = max(max_level, level)

# Recursive calls for left and right children


max_level = traverse_tree(node.left, level + 1, levels, max_level)
max_level = traverse_tree(node.right, level + 1, levels, max_level)

return max_level

def level_order(root):
if root is None:
return []

levels = {} # Dictionary to store nodes at each level


max_level = traverse_tree(root, 0, levels, 0)

# Collect the nodes from each level in order


result = [levels[level] for level in range(max_level + 1)]
return result

/////////////////////////////////////////////
//Write the code till here

def insert_level_order(arr, root, i, n):


# Base case for recursion
if i < n:
temp = TreeNode(arr[i]) if arr[i] is not None else None
root = temp

# Insert left child


if root is not None:
root.left = insert_level_order(arr, root.left, 2 * i + 1, n)

# Insert right child


if root is not None:
root.right = insert_level_order(arr, root.right, 2 * i + 2, n)

return root

arr = [3, 9, 20, None, None, 15, 7]


n = len(arr)

# Construct the binary tree


root = insert_level_order(arr, None, 0, n)

# Call levelOrder function and print the result


result = level_order(root)
print("Level Order Traversal:", result)

You might also like