LEETCODE 113 (JAVASCRIPT) | PATH SUM II

Sdílet
Vložit
  • čas přidán 30. 05. 2021
  • Hey everyone. Check out this in-depth solution for leetcode 113.

Komentáře • 4

  • @sajalgupta7345
    @sajalgupta7345 Před 2 lety +2

    Hey Andy,
    Why did we do slate.slice() on line 23. Wouldn't slate and slate.slice() be the same thing as both will returns the array only.

    • @sourenasahraian2055
      @sourenasahraian2055 Před 2 lety +2

      They are but only at that point, Arrays are passed around by reference , so any change you do the same slate instance as it gets passed around up and down the tree(future push /pop ) are also reflected into the result . You want your hard earned path solutions to be snapshots in time and remain intact . If you don't copy the array , the same address in memory gets passed around and your data will get corrupt.

    • @TekkenRoom
      @TekkenRoom Před rokem

      that's also an alternative line " paths.push([...slate])"

  • @user-pm2kx1vi1e
    @user-pm2kx1vi1e Před 7 měsíci

    /**
    * Definition for a binary tree node.
    * function TreeNode(val, left, right) {
    * this.val = (val===undefined ? 0 : val)
    * this.left = (left===undefined ? null : left)
    * this.right = (right===undefined ? null : right)
    * }
    */
    /**
    * @param {TreeNode} root
    * @param {number} targetSum
    * @return {number[][]}
    */
    var pathSum = function(root, targetSum) {
    if(!root) return [];
    const paths=[];
    const dfs = (node, sum, slate) => {
    if(node.left === null && node.right === null){
    if(sum === node.val){
    slate.push(node.val);
    paths.push(slate.slice());
    slate.pop();
    }
    }
    if(node.left){
    slate.push(node.val);
    dfs(node.left, sum - node.val, slate);
    slate.pop();
    }
    if(node.right){
    slate.push(node.val);
    dfs(node.left, sum - node.val, slate);
    slate.pop();
    }
    }
    dfs(root, targetSum, []);
    return paths;
    };;