【LeetCode】Path Sum III 解题报告

来源:互联网 发布:seo要学多久 编辑:程序博客网 时间:2024/06/05 07:26

【LeetCode】Path Sum III 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/path-sum-iii/#/description

题目描述:

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   1Return 3. The paths that sum to 8 are:1.  5 -> 32.  5 -> 2 -> 13. -3 -> 11

Ways

使用DFS解决。dfs函数有两个参数,一个是当前的节点,另一个是要得到的值。当节点的值等于要得到的值的时候说明是一个可行的解。再求左右的可行的解的个数,求和之后是所有的。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int pathSum(TreeNode root, int sum) {        if(root == null){            return 0;        }        return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);    }    public int dfs(TreeNode root, int sum){        int res = 0;        if(root == null){            return res;        }        if(root.val == sum){            res++;        }        res += dfs(root.left, sum - root.val);        res += dfs(root.right, sum - root.val);        return res;    }}

Date

2017 年 5 月 2 日

0 0