Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

437. 路径总和 III #88

Open
webVueBlog opened this issue Sep 6, 2022 · 0 comments
Open

437. 路径总和 III #88

webVueBlog opened this issue Sep 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

437. 路径总和 III

Description

Difficulty: 中等

Related Topics: , 深度优先搜索, 二叉树

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum路径 的数目。

路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

示例 1:

输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出:3
解释:和等于 8 的路径有 3 条,如图所示。

示例 2:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:3

提示:

  • 二叉树的节点个数的范围是 [0,1000]
  • -109 <= Node.val <= 109 
  • -1000 <= targetSum <= 1000 

Solution

Language: JavaScript

/**
 * 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}
 */
// DFS用来计算当前节点开始有多少符合条件的路径
// pathSum调用自己来对每一个节点进行遍历
var pathSum = function(root, targetSum) {
    if(!root) return 0
    let curNode = dfs(root,targetSum)
    let leftNode = pathSum(root.left,targetSum)
    let rightNode = pathSum(root.right,targetSum)
    return curNode+leftNode+rightNode
}

const dfs = function(root,targetSum){
    if(!root) return 0
    let res = 0
    if(root.val===targetSum) res++
    res+=dfs(root.left,targetSum-root.val)
    res+=dfs(root.right,targetSum-root.val)
    return res
}

// var pathSum = (root, targetSum) => {
//     // 深度优先遍历
//     // 参数:(当前节点,当前节点前缀和)
//     const dfs = (root, sum) => {
//         if (!root) return 0;
//         map.set(sum, (map.get(sum) || 0) + 1);
//         const newSum = sum + root.val;
//         // 寻找有无(newSum - targetSum)
//         res += map.get(newSum - targetSum) || 0;
//         // 向下遍历
//         dfs(root.left, newSum);
//         dfs(root.right, newSum);
//         // 避免相同节点值被重复计算,确保算出的sum是从上到下的一条路径
//         map.set(sum, map.get(sum) - 1);
//     };

//     // map中,key存的是前缀和,value存的是前缀和的数目
//     const map = new Map();
//     let res = 0;
//     dfs(root, 0);
//     return res;
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant