LeetCode 437. Path Sum III (路径之和之三)

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

 

 


题目标签:Tree
  这道题目给了我们一个二叉树,和一个sum,让我们找到有多少条path 的和是等于sum的,这里的path不一定要从root 到底,可以是中间的点开始到下面的点。需要另外设两个functions。
  traverseTree function - preOrder 遍历每一个点,然后把每一个点代入到findPathSum function。
  findPathSum function - 找到从root 开始到各个点的 path sum, 和sum比较,一样的话,就res++。
 
  利用traverseTree 来把每一个点(不同的level)代入findPathSum, 来找到从那个点开始往下的各种path sum,这样就可以包含 中间的点开始到下面的点的这种可能性。而且不会重复,因为每次代入的点,都是唯一的,而且找的path sum都是从这个点起始的。这两个funciton 就相当于 for loop 中间 再包括一个for loop, 来遍历array。
 
 

Java Solution:

Runtime beats 68.27% 

完成日期:07/06/2017

关键词:Tree

关键点:利用两个递归functions来搜索从每一层level 各点开始到下面层次点的path值

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     int res = 0;
13     public int pathSum(TreeNode root, int sum) 
14     {
15         if(root == null)
16             return res;
17         
18         traverseTree(root,sum);
19         
20         return res;
21     }
22     
23     public void traverseTree(TreeNode node, int sum)
24     {
25         if(node == null)
26             return;
27         
28         findPathSum(node, 0, sum);
29         traverseTree(node.left, sum);
30         traverseTree(node.right, sum);
31         
32     }
33     
34     public void findPathSum(TreeNode node, int path_sum, int sum)
35     {
36         if(node == null)
37             return;
38         
39         if(path_sum + node.val == sum)
40             res++;
41         
42         findPathSum(node.left, path_sum + node.val, sum);
43         findPathSum(node.right, path_sum + node.val, sum);
44         
45     }
46 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

转载于:https://www.cnblogs.com/jimmycheng/p/7129233.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值