LeetCode——Path Sum III
2017-11-27 19:52
232 查看
LeetCode——Path Sum III
#437You 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 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
这一题的目的是找出路径值之和等于给定值的个数。这一题第一个思路就是利用递归。
构造一个递归函数,对于树中的每个点,先判断根路径到这个节点的和是否为目标值,如果不是,则从上往下去掉一个节点的值,但要保留一个,否则为0,如果目标值为0,就会返回错误的值。从根节点开始分别递归左右子树。
C++
/** * 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) { int res = 0; vector<TreeNode*> out; helper(root,sum,0,out,res); return res; } void helper(TreeNode* Node,int sum,int cursum,vector<TreeNode*>& out,int& res) { //使用了引用作为参数 if(!Node) return; cursum += Node -> val; out.push_back(Node); if(cursum == sum) res++; int t = cursum; for(int i = 0;i < out.size() - 1;i++) { t -= out[i] -> val; if(t == sum) a28e res++; } helper(Node -> left,sum,cursum,out,res); helper(Node -> right,sum,cursum,out,res); out.pop_back(); } };
还有一种简洁的写法,也是利用了先序遍历,对于每个遍历到的节点进行处理,维护一个变量pre来记录之前路径之和,然后cur为pre加上当前节点值,如果cur等于sum,那么返回结果时要加1,然后对当前节点的左右子节点调用递归函数求解。
C++
/** * 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) { if (!root) return 0; return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); } int sumUp(TreeNode* node, int pre, int& sum) { if (!node) return 0; int cur = pre + node->val; return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum); } };
相关文章推荐
- 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 No.437 Path Sum III
- Leetcode--Path Sum I,II,III
- [LeetCode]437. Path Sum III
- LeetCode 437. Path Sum III 递归中使用递归,分两类情况
- leetcode[437] PathSum III 个人题解
- 【LeetCode】112,113,437. Path Sum I, II, III
- leetcode-437-Path Sum III
- [Leetcode] Path Sum I,II,III
- (leetcode)Path Sum III 挺有意思的一题
- LeetCode 437. Path Sum III (路径之和之三)
- leetcode_437. Path Sum III-二叉树
- Leetcode: Path Sum III
- LeetCode -- Path Sum III分析及实现方法
- LeetCode 437 Path Sum III 题解
- LeetCode - 437. Path sum III