437. 路径总和 III(java)

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

示例:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等于 8 的路径有:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:双递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
       if(root == null) return 0;
       return pathSum(root.left,sum) + pathSum(root.right,sum) + count(root, sum, 0);
    }
    public int count(TreeNode root, int sum, int n) {
        if(root == null) return 0;
        n += root.val;  
        int m = 0;
        if(sum == n) m++;
        return count(root.left, sum, n) + count(root.right, sum, n) + m;
    }
}

解法二:路径保存

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        if(root == null) return 0;
        int[] array = new int[1000];
        return count(root, sum, array, 0);
    }
    public int count(TreeNode root, int sum, int[] array, int end) {
        if(root == null) return 0;
        int tmp = root.val;
        int n = (tmp == sum)? 1 : 0;
        for(int i = end-1; i >= 0; i--){
            tmp += array[i];
            if(sum == tmp) n++;
        } 
        array[end] = root.val;
        return count(root.left, sum, array, end+1) + count(root.right, sum, array, end+1) + n;
    }
}
发布了136 篇原创文章 · 获赞 19 · 访问量 8029

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104034057
今日推荐