Java implementation LeetCode 437 sum path III (c)

437. The sum of path III

Given a binary tree, each node that are stored with an integer value.

Total number of paths to find the path and is equal to the given value.

Path does not require starting from the root, do not need to end in a leaf node, but the path direction must be down (only node from parent to child node).

No more than 1000 binary tree nodes, and the node value range is [-1000000,1000000] integer.

Example:

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

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

Returns 3. 8 have equal path:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11
/**
 * 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) {
        int [] nums = new int[1000] ;
        return pathways(root,nums,0,sum);
    }

    private int pathways(TreeNode root,int[]arr,int level,int sum)
    {
        if(root==null)
        {
            return 0 ;
        }
        int n = 0 ;
        arr[level] = root.val ;
        int a = sum ;
        int l = arr.length ;
        for(int j =level;j>=0;j--)
        {
            a -= arr[j] ;
            if(a==0)
            {
                n++;
            }
        }
        return n + pathways(root.left,arr,level+1,sum) + pathways(root.right,arr,level+1,sum);
    }
}
Released 1548 original articles · won praise 20000 + · views 2.19 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104910446