leetcode 113题

Posted by franki on February 5, 2021

leetcode 113题 路径总和 II

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例1:

给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路

深度优先搜索,记录每次遍历的路径和总和,当到达叶子节点的时候,比较总和和给定的总和是否相等,若相等就放入到结果,全部节点结束后,即可获取最终的结果。

代码

function pathSum(root, sum) {
    var res = [];
    dfs(root, res, sum);
    return res;
}

function dfs(root, res, sum, arr = [], count = 0) {
    if (!root) return null;
    count += root.val;
    arr.push(root.val);
    if (root.left) {
        dfs(root.left, res, sum, arr, count);
    }
    if (root.right) {
        dfs(root.right, res, sum, arr, count);
    }
    if (!root.left && !root.right) {
        if (count === sum) {
            res.push([...arr]);
        }
    }
    count -= root.val;
    arr.pop();
    return null;
}

复杂度分析

  • 时间复杂度: O(N^2)
  • 空间复杂度: O(N)