### 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**

- Introduction to Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree InOrder Traversal
- Binary Tree PostOrder Traversal
- Introduction to String

The Best Slots | Casino Roll

ReplyDeleteThe 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