This is a leetcode question.
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For 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] ]
But i am trying it a new way in JavaScript and not going entirely by their solution. So far i am able to print the arrays but
How can different levels be printed in new rows
Below is my code so far:
var levelOrder = function(root) {
let output = [];
let queue = [];
let currentNode = root;
queue.push(currentNode);
let currentLevel = 1;
while(queue.length){
currentNode = queue.shift();
currentLevel--; //this will ensure we are adding new lines only on next level
output.push(currentNode);
if(currentNode.left){
queue.push(currentNode.left);
}
if(currentNode.right){
queue.push(currentNode.right);
}
if(currentLevel = 0){
output = output + '/n'; //Insert a new line
currentLevel = queue.length; //2
}
}
return output;
};
Input: [3,9,20,null,null,15,7],
Expected Output:
[
[3],
[9,20],
[15,7]
]
LeetCode Question Link: BinaryTreeTraversalUsingBFS
I think you're almost there. Not sure what output = output + '/n';
is for though.
This'd pass through:
var levelOrder = function(root) {
const levels = []
if(!root) {
return levels
}
const queue = [root]
while (queue.length){
const queueLength = queue.length
const level = []
for(let i = 0; i < queueLength; i++){
const node = queue.shift()
if(node.left){
queue.push(node.left)
}
if(node.right){
queue.push(node.right)
}
level.push(node.val)
}
levels.push(level)
}
return levels
}
Base on your codebase, I modify it for work.
output = output + '/n'
, because output is an array.var levelOrder = function (root) {
let output = [];
let queue = [];
let currentNode = root;
queue.push(currentNode);
let currentLevel = 1;
let index = 0; // Add an index for increasing the output index
while (queue.length) {
currentNode = queue.shift();
currentLevel--;
if (!output[index]) { // Set default is an array for each output element in first time
output[index] = [];
}
output[index].push(currentNode.val);
if (currentNode.left) {
queue.push(currentNode.left);
}
if (currentNode.right) {
queue.push(currentNode.right);
}
if (currentLevel === 0) { // Use strict equality operator to compare 0
index++; // increase index
currentLevel = queue.length;
}
}
return output;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With