437. Path Sum III
2018-01-07 06:00
363 查看
1. Description
Given a binary tree, find the number of paths that sum to a given value.
2. Solution
The answer include three parts, the number of paths from left-child tree, the number of paths from right-child tree,
and the number of paths from the root.
How to calculate the number of paths from the root?
Use a value named current to store the current sum, when the path pass the root, add root's value to current.
Use recursive way to calculate the number.
3. Code
Given a binary tree, find the number of paths that sum to a given value.
2. Solution
The answer include three parts, the number of paths from left-child tree, the number of paths from right-child tree,
and the number of paths from the root.
How to calculate the number of paths from the root?
Use a value named current to store the current sum, when the path pass the root, add root's value to current.
Use recursive way to calculate the number.
3. Code
int pathSum(TreeNode* root, int sum) { if(root==NULL) return 0; return pathSum(root->left,sum) + pathSum(root->right,sum) + sumUp(root,0,sum); } int sumUp(TreeNode* root, int pre, int& sum){ if(!root) return 0; int current = pre + root->val; return (current == sum) + sumUp(root->left, current, sum) + sumUp(root->right, current, sum); }
相关文章推荐
- 437. Path Sum III
- 437. Path Sum III
- Leetcode算法学习日志-437 Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- [python]leetcode(437). Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- LeetCode 437 Path Sum III
- LeetCode 437 Path Sum III
- LeetCode 437 Path Sum III 题解
- 437_Path_Sum_III
- 437. Path Sum III
- LeetCode 437 Path Sum III (DFS)
- 437. Path Sum III
- LeetCode "437. Path Sum III"
- [437]. Path Sum III,[687]. Longest Univalue Path
- leetcode-437-Path Sum III
- 437. Path Sum III
- 437. Path Sum III