JavaScript recursive and non recursive solution


  • 0

    Recursion

    var levelOrder = function(root) {
      if(!root) return [];
      let levelOrderHelper = (left, right, level, ary) => {
        let nextLevel = level + 1;
        
        left && (ary[nextLevel] = ary[nextLevel] ? ary[nextLevel].concat([left.val]) : [left.val]);
        right && (ary[nextLevel] = ary[nextLevel] ? ary[nextLevel].concat([right.val]) :  [right.val]);
        
        left && levelOrderHelper(left.left, left.right, nextLevel, ary);
        right && levelOrderHelper(right.left, right.right, nextLevel, ary);
    
        return ary;
      };
      return levelOrderHelper(root.left, root.right, 0, [[root.val]]);
    };
    
    

    non-Recursion

    var levelOrder = function(root) {
        if(!root) return [];
        let row = [root];
        let returnAry = [];
        while(row && row.length > 0) {
            let nextRow = [];
            for (let i=0;i<row.length;i++) {
                row[i].left && nextRow.push(row[i].left);
                row[i].right && nextRow.push(row[i].right);
            }
            returnAry.push(row.map( (ary) => ary.val ));
            row = nextRow;
        }
        return returnAry;
    };
    
    

Log in to reply
 

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