1. 程式人生 > >437. Path Sum III

437. Path Sum III

star nta int ont pub binary ber from ins

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,問在樹中是否存在一條路徑,路徑上所有結點之和恰好等於sum。路徑不限制一定要開始於根結點或者結束於葉子結點,但是一定要是向下的(從父親結點向兒子結點)。如果存在這樣的路徑,求出有多少條

 1     int findPath(TreeNode node, int curSum, int sum) {
 2         if (node == null) return 0;
 3         curSum += node.val;
 4         int sameCount = curSum == sum ? 1 : 0;
 5         return sameCount + findPath(node.left, curSum, sum) + findPath(node.right, curSum, sum);
 6     }
 7     
 8     public
int pathSum(TreeNode root, int sum) { 9 // 以每一個節點作為路徑根節點進行前序遍歷,查找每一條路徑的權值和與sum是否相等 10 if (root == null) return 0; 11 int res = findPath(root, 0, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); 12 return res; 13 }

437. Path Sum III