leetcode#437 Path Sum III
2017-04-16 19:06
169 查看
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算法来考虑是否要将当前节点作为路径中的一个节点。对于取和不取当前节点,都要再对当前节点的左右儿子递归考察。但是,由于和是连续的,所以我们要用一个变量来记录是否可以跳过当前节点。总之,这道题就是一个简单的递归问题。
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; } };
相关文章推荐
- 非常非常非常好!path-sum-iii
- LeetCode 437. Path Sum III 题解 和固定的二叉树路径数目
- 437. Path Sum III
- LeetCode--437. Path Sum III(路径和)Python
- leetcode 437. Path Sum III
- [leetcode] 437. Path Sum III 解题报告
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)
- [LeetCode] 437. Path Sum III 路径和 III
- leetcode-437-Path Sum III
- LeetCode-437. Path Sum III
- [python]leetcode(437). Path Sum III
- Path Sum III
- LeetCode "437. Path Sum III"
- LeetCode - 437. Path sum III
- [437]. Path Sum III,[687]. Longest Univalue Path
- 437_Path_Sum_III
- LeetCode 437. Path Sum III
- leetcode[Path Sum III]//待整理多种解法
- 437. Path Sum III
- 【二叉树】437. Path Sum III(理解递归)