Short DFS Javascript solution


  • 0
    E
    1. Assume the tree depth is no more than 100
    2. Generate an array (col x row) using DFS traversal
    3. Clean up the array by removing undefined items
    var verticalOrder = function(root) {
      var res = [];
      var traverse = (node, col, row) => {
        if (node) {
          traverse(node.left, col-1, row+1);
          traverse(node.right, col+1, row+1);
          res[col] = res[col] || [];
          res[col][row] = res[col][row] || [];
          res[col][row].push(node.val);
        }
      };
      traverse(root, 100, 0);
      res = res.filter(Array).map(arr=>arr.reduce((a,b)=>a.concat(b)));
      return res;
    };
    

Log in to reply
 

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