coding-interview|November 19, 2020|1 min read

Binary Tree - Level Order Traversal

TL;DR

Use a queue (BFS) — enqueue the root, then dequeue each node and enqueue its children. Each dequeue gives you the next node in level order. O(n) time and space.

Binary Tree - Level Order Traversal

Problem Statement

Given a Binary tree, print out nodes in level order traversal from left to right.

        50
      /    \
    80      30
  /    \      \
20     40      10

# Output
# 50 80 30 20 40 10

Approach-1

Use BFS (Breadth First Search) algorithm. Since, it reaches out to nodes first that are immediate neighbours.

Idea is to take a queue, keep accumulating queue for each child.

void bfs(Node node) {
  Queue<Node> q = new Queue();
  q.add(node);

  while (!q.isEmpty()) {    
    Node n = q.pop();
    print(n);

    if (n.left != null) q.add(n.left);
    if (n.right != null) q.add(n.right);
  }
}

The Complexity is O(n) as we are visiting each nodes only once.

Approach-2

You can prepare a list of nodes at each level. We will also use DFS (Depth First Search) algorithm here.

void levelOrder(Node node, List<List<Node>> list, int level) {
    if (node == null)
      return;
    List<Node> levelList = list.get(level);
    if (levelList == null) {
      levelList = new ArrayList();
      list.add(levelList);
    }
    levelList.add(node);

    levelOrder(node.left, list, level+1);
    levelOrder(node.right, list, level+1);
 }

List<List<Node>> list = new ArrayList();
levelOrder(root, list, 0);

After this, we can print the list.

The Complexity is O(n) as we are visiting each nodes only once.

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…