437:路径总和 III

This commit is contained in:
huangge1199@hotmail.com 2021-09-28 22:40:10 +08:00
parent 7c122c490d
commit bd640f02f7
2 changed files with 124 additions and 0 deletions

View File

@ -0,0 +1,91 @@
//给定一个二叉树的根节点 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]
// -10 <= Node.val <= 10
// -1000 <= targetSum <= 1000
//
// Related Topics 深度优先搜索 二叉树 👍 1091 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
//437:路径总和 III
class PathSumIii {
public static void main(String[] args) {
//测试代码
Solution solution = new PathSumIii().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int pathSum(TreeNode root, int targetSum) {
if (root == null) {
return 0;
}
int ret = rootSum(root, targetSum);
ret += pathSum(root.left, targetSum);
ret += pathSum(root.right, targetSum);
return ret;
}
public int rootSum(TreeNode root, int targetSum) {
int ret = 0;
if (root == null) {
return 0;
}
int val = root.val;
if (val == targetSum) {
ret++;
}
ret += rootSum(root.left, targetSum - val);
ret += rootSum(root.right, targetSum - val);
return ret;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,33 @@
<p>给定一个二叉树的根节点 <code>root</code> ,和一个整数 <code>targetSum</code> ,求该二叉树里节点值之和等于 <code>targetSum</code><strong>路径</strong> 的数目。</p>
<p><strong>路径</strong> 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<p><img src="https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" style="width: 452px; " /></p>
<pre>
<strong>输入:</strong>root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
<strong>输出:</strong>3
<strong>解释:</strong>和等于 8 的路径有 3 条,如图所示。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
<strong>输出:</strong>3
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>二叉树的节点个数的范围是 <code>[0,1000]</code></li>
<li><meta charset="UTF-8" /><code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code> </li>
<li><code>-1000 <= targetSum <= 1000</code> </li>
</ul>
<div><div>Related Topics</div><div><li></li><li>深度优先搜索</li><li>二叉树</li></div></div><br><div><li>👍 1091</li><li>👎 0</li></div>