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).

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

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<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i=0; i< size; i++){
                TreeNode curr = queue.poll();
                tmp.add(curr.val);
                if(curr.left != null) queue.offer(curr.left);
                if(curr.right != null) queue.offer(curr.right);
            }
            ans.add(tmp);
        }
        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.

Comments

  1. The Best Slots | Casino Roll
    The best slots at ventureberg.com/ Casino Roll. If you https://febcasino.com/review/merit-casino/ love table games, to poormansguidetocasinogambling play blackjack, you have to 바카라 사이트 bet twice for the dealer to win. The https://septcasino.com/review/merit-casino/ dealer must

    ReplyDelete

Post a Comment

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala