Binary Tree Level Order Traversal - The Coding Shala

Last Updated: 19-Jan-2021
Home >> Data Structures >> Binary Tree Level Order Traversal

 In this post, we will learn how to Traverse a Binary Tree in Level Order.

Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Given binary tree [3,9,20,null,null,15,7],
   / \
  9  20
    /  \
   15   7
return its level order traversal as:

Level Order Traversal of Binary Tree in Java

Approach 1

Using Queue[BFS]. Iterative Solution.

Java Program: 

 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) return ans;
        Queue<TreeNode> queue = new LinkedList<>();
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i=0; i< size; i++){
                TreeNode curr = queue.poll();
                if(curr.left != null) queue.offer(curr.left);
                if(curr.right != null) queue.offer(curr.right);
        return ans;

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


  1. The Best Slots | Casino Roll
    The best slots at Casino Roll. If you love table games, to poormansguidetocasinogambling play blackjack, you have to 바카라 사이트 bet twice for the dealer to win. The dealer must


Post a Comment

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala