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

posted @ 2017-07-07 00:59  Jimmy_Cheng  阅读(277)  评论(0编辑  收藏  举报