437. Path Sum III

Easy

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 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
package leetcode.easy;

/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
public class PathSumIII {
int count = 0; private void helper(TreeNode root, int sum) {
if (root == null) {
return;
} if (root.val == sum) {
count++;
} if (root.left != null) {
helper(root.left, sum - root.val);
} if (root.right != null) {
helper(root.right, sum - root.val);
}
} public int pathSum(TreeNode root, int sum) {
if (root == null) {
return count;
}
helper(root, sum);
if (root.left != null) {
pathSum(root.left, sum);
}
if (root.right != null) {
pathSum(root.right, sum);
}
return count;
} @org.junit.Test
public void test() {
int sum = 8;
TreeNode tn11 = new TreeNode(10);
TreeNode tn21 = new TreeNode(5);
TreeNode tn22 = new TreeNode(-3);
TreeNode tn31 = new TreeNode(3);
TreeNode tn32 = new TreeNode(2);
TreeNode tn34 = new TreeNode(11);
TreeNode tn41 = new TreeNode(3);
TreeNode tn42 = new TreeNode(-2);
TreeNode tn44 = new TreeNode(1);
tn11.left = tn21;
tn11.right = tn22; tn21.left = tn31;
tn21.right = tn32;
tn22.left = null;
tn22.right = tn34; tn31.left = tn41;
tn31.right = tn42;
tn32.left = null;
tn32.right = tn44;
tn34.left = null;
tn34.right = null; tn41.left = null;
tn41.right = null;
tn42.left = null;
tn42.right = null;
tn44.left = null;
tn44.right = null;
System.out.println(pathSum(tn11, sum));
}
}

最新文章

  1. 哆啦A梦 canvas
  2. SVG的使用
  3. 今天学习到的关于mysql数据库的linux命令
  4. POJ 3414 Pots ( BFS , 打印路径 )
  5. 寻找最大的k个数
  6. Ubuntu + VMware=Linux虚拟机
  7. [0] CollectionBase与索引符DictionaryBase与迭代器
  8. 【日常学习】【IDA*】codevs2449 骑士精神题解
  9. visual studio 2013 几个测试工具(Nunit 3、xUnit)
  10. matlab练习程序(点集配准的SVD法)
  11. PAT L2-007 家庭房产
  12. python3+selenium入门05-元素操作及常用方法
  13. BZOJ.4558.[JLOI2016]方(计数 容斥)
  14. NO.10: 在operator=中处理 "自我赋值"
  15. YII2中actions的作用与使用
  16. [翻译] About Core Image
  17. 互评Alpha版本——基于spec评论作品
  18. UVA 11367 Full Tank?(bfs最短路)
  19. hibernate缓存机制(转载)
  20. 零散知识点总结(持续更新……)

热门文章

  1. Optimal Marks SPOJ - OPTM(最小割)
  2. python 字符串方法整理
  3. learning svn diff --summarize
  4. 移动端tap事件(轻击、轻触)
  5. 洛谷 P3371 【模板】单源最短路径(弱化版) 题解
  6. Ajax.BeginForm 不执行OnSuccess
  7. Cocos CreatorUI系统下
  8. delphi开第二个进程报错cannot create file editorlineends.ttr
  9. C++ 类型转换符区别分析
  10. Shell脚本实现对文件编辑