6

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

1

4 Answers 4

9

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
}

References

  • For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Sign up to request clarification or add additional context in comments.

1 Comment

That;s a great solution you hit the bulls eye. I am new to Javascript, so basically you have level array and you are pushing this array to parent array-levels each time child nodes are complete. New line doesn't matter here for arrays it's just for the display, but i suppose if we need to show it as a string then new line has to be entered. Thank you.
2

Base on your codebase, I modify it for work.

  • Add an index for increasing the output index.
  • Use strict equality operator instead of assignment variable.
  • Remove 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;
};

1 Comment

I think your code will not work for this input : Input [1,2,3,4,null,null,5] stdout 1 [ [ 1 ], [ 2, 3 ], [ 4 ], [ 5 ] ] Output [[1],[2,3],[4],[5]] Expected [[1],[2,3],[4,5]]
0

This is the recursion solution to it

    var levelOrder = function(root) {
    let result =[];
    if(!root)return result;
    if(!root.left && !root.right){
        result.push([root.val]);
        return result;
    }
    const pushIntoResult =(node, level) =>{
        if(!node) return;
        if(!result[level]){
            result.push([]);
        }
        result[level].push(node.val);
        pushIntoResult(node.left, level+1);
        pushIntoResult(node.right, level+1);
    }
    pushIntoResult(root, 0);
    return result;
};

Comments

0

You may try this bit modification in @Ahmad Atrach' code

const dfs = (node,result,level) => {

if(!node) return;
if(!result[level]){
    result.push([]);
}
result[level].push(node.val);
dfs(node.left,result, level+1);
dfs(node.right,result, level+1);
}
var levelOrder = function(root) {

  if(!root) return [];
  let result = [];
  dfs(root,result,0);

  return result;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.