【leetcode c++】 112 Path Sum
2015-07-31 23:27
477 查看
Path Sum
Given a binary tree and a sum, determine ifthe tree has a root-to-leaf path such that adding upall the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
return true, as there exist a root-to-leafpath 5->4->11->2 which sum is 22.
我依然使用递归的方法去遍历,但是,考虑一下,这题有情况是在未全部遍历的情况下找到一条路径了,则后面的遍历就不需要了,我们可以考虑避免一些多余的遍历。
考虑递归的传参,首先要传一个sum,也就是我们要找的和,其次要传一个整型的引用,来表示当前节点为止的和,然后,到达叶子节点之后判断这两个和是否相等。最后,在递归函数的末尾还要减掉当前节点的值。
Given a binary tree and a sum, determine ifthe tree has a root-to-leaf path such that adding upall the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
return true, as there exist a root-to-leafpath 5->4->11->2 which sum is 22.
我依然使用递归的方法去遍历,但是,考虑一下,这题有情况是在未全部遍历的情况下找到一条路径了,则后面的遍历就不需要了,我们可以考虑避免一些多余的遍历。
考虑递归的传参,首先要传一个sum,也就是我们要找的和,其次要传一个整型的引用,来表示当前节点为止的和,然后,到达叶子节点之后判断这两个和是否相等。最后,在递归函数的末尾还要减掉当前节点的值。
/** * 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: bool hasPathSum(TreeNode* root, int sum) { int preSum = 0; bool hasRes = false; Lv(root, sum, preSum, hasRes); return hasRes; } void Lv(TreeNode* root,int sum, int& preSum, bool& hasRes) { if(hasRes) return; if(NULL == root) return; preSum += root->val; if(!root->left && !root->right) { if(sum == preSum) { hasRes = true; return; } } Lv(root->left, sum, preSum, hasRes); Lv(root->right, sum, preSum, hasRes); preSum -= root->val; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解