leetcode 437. Path Sum III

来源:互联网 发布:网络变压器怎么接线 编辑:程序博客网 时间:2024/06/17 03:28

原题:

ou 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
思路:

基本的dfs,然而很久没写过,还是对其中许多控制的部分想了一些时间。

代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int pathSum(struct TreeNode* root, int sum) {    if(root==NULL)        return 0;    int listsum=0;    int *times;    times=(int*)malloc(sizeof(int));    *times=0;    int depth(struct TreeNode* root,int listsum,int* times,int sum);    depth(root,listsum,times,sum);    return *times+pathSum(root->left,sum)+pathSum(root->right,sum);    }int depth(struct TreeNode* root,int listsum,int* times,int sum){    if(root==NULL)        return 0;    if(listsum+root->val==sum)    {        *times+=1;    }    listsum+=root->val;    //printf("%d,",listsum);    depth(root->left,listsum,times,sum);    depth(root->right,listsum,times,sum);    return 0;}