You've successfully subscribed to Nicholas Workshop
Great! Next, complete checkout for full access to Nicholas Workshop
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Print Binary Tree Layer-by-layer

Nicholas Wong
Nicholas Wong

Question

Print a binary tree layer-by-layer from top to bottom, and from left to right for each layer.

Solution

Yes, it’s a simple task. We can use breadth-first search, and which means we need a queue.

Example

# node structure 
class bst_node: 
    def __init__(self, value, left=None, right=None): 
        self.value = value 
        self.left = left 
        self.right = right
        
# what to do with a node. 
def visit(node): 
    print node.value, # bfs traversal 

def breadth_first_traversal(root): 
    queue = [root] 
    while len(queue) > 0: 
        node = queue.pop(0) # get the head item 
        visit(node) 
        if node.left: queue.append(node.left) 
        if node.right: queue.append(node.right) 
        
# a binary tree and display how was it before reflection 
node_05 = bst_node(5)
node_07 = bst_node(7)
node_09 = bst_node(9)
node_11 = bst_node(11)
node_06 = bst_node(6, node_05, node_07)
node_10 = bst_node(10, node_09, node_11)
node_08 = bst_node(8, node_06, node_10) 
root = node_08 

# answer should be: 8 6 10 5 7 9 11 
breadth_first_traversal(root)
Algorithm

Nicholas Wong

Fullstack software engineer with strong background in computer science and extensive experience in software engineering and architecture. Studied in NYU, worked in Yahoo, Rakuten and Manulife.