Path Sum III

Posted nickyye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Path Sum III相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode: Path Sum III

Path Sum III Leetcode

[LeetCode] Path Sum III

Path Sum III

437. Path Sum III

437. Path Sum III