Easy to Understand JavaScript Solution


  • 0
    H

    Basically using BFS, I have queue which stores arrays containing [node, depth].

    var levelOrder = function(root) {
      var result = [];
      var queue = [[root, 0]];
      var node, depth;
    
      if (!root)  return result;
    
      while (queue.length) {
        task = queue.shift();
    
        node = task[0];
        depth = task[1];
    
        if (!Array.isArray(result[depth])) result[depth] = [];
        
        result[depth].push(node.val);
    
        if (node.left) queue.push([node.left, depth + 1]);
        if (node.right) queue.push([node.right, depth + 1]);
      }
    
      return result;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.