【LeetCode】Path Sum III 解题报告
来源:互联网 发布:seo要学多久 编辑:程序博客网 时间:2024/06/05 07:26
【LeetCode】Path Sum III 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/path-sum-iii/#/description
题目描述:
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \3 -2 1Return 3. The paths that sum to 8 are:1. 5 -> 32. 5 -> 2 -> 13. -3 -> 11
Ways
使用DFS解决。dfs函数有两个参数,一个是当前的节点,另一个是要得到的值。当节点的值等于要得到的值的时候说明是一个可行的解。再求左右的可行的解的个数,求和之后是所有的。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int pathSum(TreeNode root, int sum) { if(root == null){ return 0; } return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } public int dfs(TreeNode root, int sum){ int res = 0; if(root == null){ return res; } if(root.val == sum){ res++; } res += dfs(root.left, sum - root.val); res += dfs(root.right, sum - root.val); return res; }}
Date
2017 年 5 月 2 日
0 0
- [leetcode] 437. Path Sum III 解题报告
- 【LeetCode】Path Sum III 解题报告
- [Leetcode] 437. Path Sum III 解题报告
- Leetcode 437. Path Sum III 路径和3 解题报告
- [LeetCode]Path Sum,解题报告
- 【LeetCode】Path Sum 解题报告
- LeetCode-Combination Sum III-解题报告
- [leetcode] 216. Combination Sum III 解题报告
- LeetCode 216. Combination Sum III 解题报告
- [Leetcode] 216. Combination Sum III 解题报告
- [LeetCode]Minimum Path Sum,解题报告
- 【LeetCode】Minimum Path Sum 解题报告
- 【LeetCode】Path Sum II 解题报告
- [leetcode] 64. Minimum Path Sum 解题报告
- [leetcode] 112. Path Sum 解题报告
- [leetcode] 113. Path Sum II 解题报告
- [LeetCode] Minimum Path Sum 解题报告
- [LeetCode] Path Sum II 解题报告
- 各大音乐网站接口
- 设计模式03:抽象工厂
- springmvc使用拦截器
- TensorsFlow学习笔记4----面向机器学习专家的深度MNIST教程(Deep MNIST for Experts)
- android 广播的使用
- 【LeetCode】Path Sum III 解题报告
- JDBC
- Python3 random(伪随机数 模块)
- JS的Ajax
- C# 正则表达式
- RabbitMQ之镜像队列
- web.js.arguments的使用
- 134. Gas Station
- JNI点滴