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;}
阅读全文
0 0
- LeetCode 437. Path Sum III
- LeetCode 437. Path Sum III
- LeetCode 437. Path Sum III
- leetcode 437. Path Sum III
- [LeetCode]437. Path Sum III
- 【LeetCode】 437. Path Sum III
- [leetcode]437. Path Sum III
- LeetCode 437. Path Sum III
- [leetcode]437. Path Sum III
- [LeetCode]437. Path Sum III
- Leetcode-437. Path Sum III
- Leetcode-437. Path Sum III
- LeetCode-437. Path Sum III
- 【Leetcode】437. Path Sum III
- 【Leetcode】437. Path Sum III
- Leetcode 437. Path Sum III
- [LeetCode]437. Path Sum III
- [leetcode]: 437. Path Sum III
- iOS 项目中SDK的开发
- 析测结Trimble TILOS v9.0 1CD
- 聊聊并发-Java中的Copy-On-Write容器
- 一文理清区块链里那些容易混淆的概念
- 【机器学习-西瓜书】九、K-means;聚类算法划分
- leetcode 437. Path Sum III
- QML 进阶---Coordinate Transformations
- 1.1.3 memcachedb
- 至走在路上的人
- 牛客正则表达式练习题(持续更新)
- GCD 保证顺序上传下载
- 算法:在二叉树中寻找两个节点的共同祖先
- c# WEBSERVICE
- [LeetCode P97] Interleaving String动态规划