JavaScript solution using BFS


  • 0
    P
    const largestValues = function(treeRoot) {
      const result = [];
    
      // edge case
      if (!treeRoot) {
        return result;
      }
    
      // breadth first search so use queue
      let queue = [];
      let nextRow = [];
      let max = -Infinity;
    
      // helper function to deal with each node
      function treeNodeProcessor(tree) {
        if (tree.val > max) {
          max = tree.val;
        }
        if (tree.left) {
          nextRow.push(tree.left);
        }
        if (tree.right) {
          nextRow.push(tree.right);
        }
      }
    
      // helper function to reset row
      function handleBreak() {
        result.push(max);
        queue = nextRow;
        nextRow = [];
        max = -Infinity;
      }
    
      treeNodeProcessor(treeRoot);
      handleBreak();
    
      while (queue.length) {
        queue.push('break');
        let shiftedNode = queue.shift();
        shiftedNode === 'break' ? handleBreak() : treeNodeProcessor(shiftedNode);
      }
    
      return result;
    };
    

Log in to reply
 

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