Print the nodes in a binary tree level-wise
December 24, 2023
Problem #
Print the nodes in a binary tree level-wise. For example, the following should print 1, 2, 3, 4, 5.
1
/ \
2 3
/ \
4 5
Solution #
Here is the Python code to print the nodes of a binary tree level-wise:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printLevelOrder(root):
if not root:
return
queue = []
queue.append(root)
while queue:
node = queue.pop(0)
print(node.val, end=", ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# Driver code
# Creating the binary tree from the example
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(5)
# Print level order traversal
printLevelOrder(root)
When executed, this code will print the nodes in the binary tree level-wise as 1, 2, 3, 4, 5,
.