leetcode#437 Path Sum III
来源:互联网 发布:上古卷轴5御姐捏脸数据 编辑:程序博客网 时间:2024/06/08 11:33
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.
对于这个题目,我们可以考虑用dp算法来考虑是否要将当前节点作为路径中的一个节点。对于取和不取当前节点,都要再对当前节点的左右儿子递归考察。但是,由于和是连续的,所以我们要用一个变量来记录是否可以跳过当前节点。总之,这道题就是一个简单的递归问题。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int pathSum(TreeNode* root, int sum) { return path(root, sum, true); } int path(TreeNode* root, int sum, bool flag) { if (!root) return 0; int here = 0; if (root->val == sum) { here = 1; } int left1=0, left2=0, right1=0, right2=0; if (root->left) { left1 = path(root->left, sum - root->val, false); if (flag) left2 = path(root->left, sum, true); } if (root->right) { right1 = path(root->right, sum - root->val, false); if (flag) right2 = path(root->right, sum, true); } return here + left1 + left2 + right1 + right2; }};
0 0
- LeetCode 437 Path Sum III
- leetcode-437-Path Sum III
- leetcode#437 Path Sum III
- LeetCode 437 Path Sum III
- LeetCode-Path Sum III
- path sum iii-leetcode
- Path Sum III ---LeetCode
- Leetcode | Path Sum III
- Leetcode Path Sum III
- LEETCODE--Path Sum III
- LeetCode -- Path Sum III
- LeetCode : Path Sum III
- LeetCode 437 Path Sum III (DFS)
- LeetCode No.437 Path Sum III
- LeetCode #437 - Path Sum III - Medium
- LeetCode 437 Path Sum III 题解
- [python]leetcode(437). Path Sum III
- LeetCode 437. Path Sum III
- 漫步数理统计十七——条件分布与期望
- leetcode64. Minimum Path Sum
- Entity层
- 安装mysql后重新设置密码
- 等差素数列
- leetcode#437 Path Sum III
- Educational Codeforces Round 19 B. Odd sum
- unity3d用欧拉角(eulerAngles)给刚体直接加速度(velocity )的算法举例
- javascript---生成器(generator)
- KMP算法
- 设计模式-访问者模式
- python调用matlab环境配置,非常详细!!!
- java 类加载-初始化顺序
- ZOJ2388 Beat the Spread!