Level Order Traversal of Binary Tree
Given the root of a binary tree, display its level-order traversal.
Statement
Given the root of a binary tree, display the values of its nodes while performing a level-order traversal. We must print node values for all levels separated by the specified character, :
.
Example
Let’s look at the tree below as an example:
The level-order traversal for the above tree will look like this:
100 : 50, 200 : 25, 75, 350
Sample Input
The input list below represents the level-order traversal of the binary tree:
[100, 50, 200, 25, 75, 350]
Expected Output
The sequence below represents the level-order traversal of the binary tree we expect to print:
100 : 50, 200 : 25, 75, 350
Try it yourself
Note: The binary tree node’s class has members
left
andright
to store references to other nodes, along with the memberdata
to hold the node’s value.
#include "BinaryTree.cpp"#include <queue>using namespace std;void LevelOrderTraversal(BinaryTreeNode* root) {// TODO: Write - Your - Codecout << "";}
Solution 1
We need two queues to solve this problem:
- The current queue
- The next queue
We will conform to the following steps for this solution:
-
First, we declare an array of two queues. This step will help us, later on, to swap values between our two queues.
-
We then declare and point the current queue to the ...