题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
http://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
Java-递归
import java.util.*;
public class Solution {
// 计算以root为根的树中路径和为sum的路径总数
public int FindPath(TreeNode root, int sum) {
// write code here
if (root == null) {
return 0;
}
int startAtRoot = Find(root, sum, 0);
int l = FindPath(root.left, sum);
int r = FindPath(root.right, sum);
return l + r + startAtRoot;
}
// 计算以root为起点,到其某个子节点的路径和为sum的路径数
public int Find(TreeNode root, int sum, int temp) {
if (root == null) {
return 0;
}
int count = 0;
if (sum == temp + root.val) {
count = 1;
}
temp += root.val;
int l = Find(root.left, sum, temp);
int r = Find(root.right, sum, temp);
return l + r + count;
}
}