码迷,mamicode.com
首页 > 其他好文 > 详细

Path Sum III

时间:2018-11-17 00:26:27      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:div   which   more   com   style   时间   code   path sum   example   

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

标签:div   which   more   com   style   时间   code   path sum   example   

原文地址:https://www.cnblogs.com/NickyYe/p/9972448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!