给定一个二叉树root和一个整数值 sum ,求该树有多少路径的的节点值之和等于 sum 。
1.该题路径定义不需要从根节点开始,也不需要在叶子节点结束,但是一定是从父亲节点往下到孩子节点
2.总节点数目为n
3.保证最后返回的路径个数在整形范围内(即路径个数小于231-1)
数据范围:
0<=n<=10000<=n<=1000
-10^9<=节点值<=10^9−109<=节点值<=109
假如二叉树root为{1,2,3,4,5,4,3,#,#,-1},sum=6,那么总共如下所示,有3条路径符合要求
思路:二次递归,一次是遍历每个节点,还要一次是以当前节点为根节点,找合适的路径
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型
*/
public static int res = 0;//res用来统计数目
public int FindPath (TreeNode root, int sum) {
// write code here
if(root==null) return 0;
show(root,sum);
return res;
}
//遍历所有的节点
private void show(TreeNode root,int sum){
if(root==null) return;
func(root,0,sum);
if(root.left!=null) show(root.left,sum);
if(root.right!=null) show(root.right,sum);
}
//将每个节点作为根节点,进行查找(回溯)
private void func(TreeNode root,int count,int sum){
//if(root.left==null&&root.right==null) return;
count+=root.val;
if(sum==count){
res = res+1;
}
if(root.left!=null) func(root.left,count,sum);
if(root.right!=null) func(root.right,count,sum);
if(root.left==null&&root.right==null) return;
}
}