Leetcode 437. Path Sum III
2017-07-13 10:39
441 查看
题目:
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);
}
}
};
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);
}
}
};
相关文章推荐
- 【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(路径和)Python
- 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(路径和)(DFS)
- LeetCode 437. Path Sum III (STL map前缀和)
- LeetCode - 437. Path sum III
- Leetcode 437. Path Sum III (Easy) (cpp)
- [LeetCode] 437. Path Sum III 路径和 III
- Leetcode-437. Path Sum III
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)