[LeetCode] 437. Path Sum III
来源:互联网 发布:php artisan 安装 编辑:程序博客网 时间:2024/06/05 10:31
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
class Solution {public: int pathSum(TreeNode* root, int sum) { stack<TreeNode *> stk; int cnt = 0; TreeNode *ptn = root; while (!stk.empty() || ptn != nullptr) { if (ptn != nullptr) { stk.push(ptn); ptn = ptn->left; } else { ptn = stk.top(); stk.pop(); cnt += __pathSum(ptn, sum); ptn = ptn->right; } } return cnt; }private: int __pathSum(TreeNode* root, int sum) { if (root == nullptr) return 0; int cnt = 0; cnt += (root->val == sum); cnt += __pathSum(root->left, sum - root->val); cnt += __pathSum(root->right, sum - root->val); return cnt; }};
class Solution {public: int pathSum(TreeNode* root, int sum) { if (root == nullptr) return 0; return SumUp(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); }private: int SumUp(TreeNode* root, int sum) { if (root == nullptr) return 0; int cnt = 0; cnt += root->val == sum; cnt += SumUp(root->left, sum - root->val); cnt += SumUp(root->right, sum - root->val); return cnt; }};
阅读全文
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
- 5.7-全栈Java笔记:字符串String的常用方法
- ptyhon 类的继承和定制类
- node
- java递归实现两个小例子
- IDEA Tomcat启动报错Error:java: Compilation failed: internal java compiler error
- [LeetCode] 437. Path Sum III
- linux命令(一)
- 使用笔记本搭建服务器(外网可以访问)
- 如何判断请求是否是AJAX请求
- vuex
- 命令模式
- 在table中使显示的文本显示一行后其余用省略号表示
- 利用栈求表达式的值(数据结构课程设计)
- 如何选择python版本