Given the root of a binary tree, display the node values at each level. Node values for all levels should be displayed on separate lines. Let’s take a look at the below binary tree.
Level order traversal for this tree should look like: 100; 50, 200; 25, 75, 350
def level_order_traversal(root):result = ""#TODO: Write - Your - Codereturn result
from collections import dequedef level_order_traversal(root):result = []if not root:result = "None"return resultqueue = deque()queue.append(root)while queue:level_size = len(queue)level_nodes = []for _ in range(level_size):temp = queue.popleft()level_nodes.append(str(temp.data))if temp.left:queue.append(temp.left)if temp.right:queue.append(temp.right)result.append(", ".join(level_nodes))return "; ".join(result)arr = [100,50,200,25,75,350]root = create_BST(arr)print("InOrder Traversal:", end = "")display_inorder(root)print("\nLevel Order Traversal: ", level_order_traversal(root))
The runtime complexity of this solution is linear, .
The memory complexity of this solution is linear, .
Initialize a queue, queue
, with the root node.
Iterate over the queue
until it’s empty:
(level_size)
of the queue.level_nodes
.level_size
times:
queue
.level_nodes
.queue
, if they exist.level_nodes
to a comma-separated string and store it in result
.Return the result
.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!