0437. Path Sum III (M)
阿新 • • 發佈:2020-08-09
Path Sum III (M)
題目
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
題意
在給定的樹中找到一條從上到下的路徑,使其和為給定值。路徑的起點和終點可以是任意結點。
思路
雙重遞迴。第一重遞迴確定根結點,限制需要查詢的子樹;第二重遞迴在該子樹中找到從子樹根結點出發和為sum的路徑的個數。
程式碼實現
Java
/** * 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 sum) { if (root == null) { return 0; } return findPath(root, 0, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int findPath(TreeNode root, int curSum, int sum) { if (root == null) { return 0; } curSum += root.val; return (curSum == sum ? 1 : 0) + findPath(root.left, curSum, sum) + findPath(root.right, curSum, sum); } }