Leetcode 437. Path Sum III
来源:互联网 发布:stddev sqlserver 编辑:程序博客网 时间:2024/06/15 19:51
题目:
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.
思路:每一个节点都可能成为所求路径的头节点,所以要遍历每个节点,结果就是一每个节点为头的所有满足路径数目之和,递归求解。
class Solution {public: int sumN(TreeNode* root,int sum,int cur) { if(root == NULL) return 0; if(root->val+cur == sum) { return 1+sumN(root->left,sum,cur+root->val)+sumN(root->right,sum,cur+root->val); } else { return sumN(root->left,sum,cur+root->val)+sumN(root->right,sum,cur+root->val); } } int pathSum(TreeNode* root, int sum) { if(root ==NULL) { return 0; } else { return sumN(root,sum,0)+pathSum(root->left,sum)+pathSum(root->right,sum); } }};
阅读全文
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
- “System.Web.HttpException”类型的异常在 System.Web.dll
- vue开发:vue2.0开发中常见问题
- 1057 N的阶乘(bignum)
- ubuntu16.04 Nvidia 显卡的风扇调速及startx的后果
- Android Wi-Fi Disable Roaming in wpa_supplicant
- Leetcode 437. Path Sum III
- Dialog响应WM_CHAR消息
- js常用正则表达式
- Java 之 Socket通信(一)
- Android 加权限
- Android开发中在线程(非主线程)中更改视图
- python 某公司机试题小记
- Android Studio安装
- 关于语音动画加上JS点击控制的方式