1. 程式人生 > >Path Sum III

Path Sum III

子節點 path sum you .com tree lee div tps sta

https://leetcode.com/problems/path-sum-iii

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的,就算一個。

這樣做的時間復雜度是O(n^2)。

/**
 * 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[] count = new int[1]; count(root, sum, count); if (root != null) { count[0] += pathSum(root.left, sum); count[0] += pathSum(root.right, sum); } return count[0]; } public void count(TreeNode root, int sum, int[] count) { if (root == null) { return; } if (root.val == sum) { count[0]++; } if (root.left != null) { count(root.left, sum - root.val, count); } if (root.right != null) { count(root.right, sum - root.val, count); } } }

Path Sum III