LeetCode112. Path Sum(Easy)
2017-09-20 20:52
309 查看
原题地址:https://leetcode.com/problems/path-sum/description/
题目描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all 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-leaf path 5->4->11->2 which sum is 22.
题解:
先序遍历也是二叉树上的一种DFS, 这道题就直接按先序遍历的顺序,用一个变量存储累加值,和sum比较如果相等就返回True。
在向下一层遍历时使用了if (hasPathSum(root->left, sum)) return true这样的格式,可以保证只在返回True时才一路返回到最顶层,而在返回False时只回到上一层,当所有节点遍历完之后再返回False。于是代码如下:
114 / 114 test cases passed.
Status: Accepted
Runtime: 13 ms
再看其他人的算法,思路大致都一样,但是在处理方式上有更简单的表达,那就是在每向下一层遍历时,用sum减去当前节点的值,当sum等于当前叶子节点的值后,就找到了路径。这样避免了创建一个新的参数保存每一层累加的值,且不需要每次返回上一层时再将当前节点的值减去。
代码如下:
114 / 114 test cases passed.
Status: Accepted
Runtime: 9 ms
题目描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
题解:
先序遍历也是二叉树上的一种DFS, 这道题就直接按先序遍历的顺序,用一个变量存储累加值,和sum比较如果相等就返回True。
在向下一层遍历时使用了if (hasPathSum(root->left, sum)) return true这样的格式,可以保证只在返回True时才一路返回到最顶层,而在返回False时只回到上一层,当所有节点遍历完之后再返回False。于是代码如下:
class Solution { public: int sums = 0; bool hasPathSum(TreeNode* root, int sum) { if (root != NULL) sums += root->val; else return false; if (sums == sum&&root->left == NULL&&root->right == NULL) return true; if (root->left != NULL) if (hasPathSum(root->left, sum)) return true; if (root->right != NULL) if (hasPathSum(root->right, sum)) return true; if (root != NULL) sums -= root->val; return false; } };
114 / 114 test cases passed.
Status: Accepted
Runtime: 13 ms
再看其他人的算法,思路大致都一样,但是在处理方式上有更简单的表达,那就是在每向下一层遍历时,用sum减去当前节点的值,当sum等于当前叶子节点的值后,就找到了路径。这样避免了创建一个新的参数保存每一层累加的值,且不需要每次返回上一层时再将当前节点的值减去。
代码如下:
class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (root == NULL) return false; if (root->val == sum&&root->left == NULL&&root->right == NULL) return true; sum -= root->val; return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); } };
114 / 114 test cases passed.
Status: Accepted
Runtime: 9 ms
相关文章推荐
- 【LeetCode】112.Path Sum(Easy)解题报告
- Leetcode 112. Path Sum (Easy) (cpp)
- LeetCode 112. Path Sum
- 【LeetCode】112. Path Sum Java,C++,解法及注释
- [LeetCode] 112. Path Sum
- [leetcode] 112. Path Sum
- Leetcode[Easy] - Path Sum
- Leetcode 112. Path Sum
- Leetcode 112. Path Sum
- LeetCode 112. Path Sum
- 【一天一道LeetCode】#112. Path Sum
- Leetcode 112. Path Sum
- [LeetCode]112. Path Sum
- [leetcode] 112.Path Sum
- LeetCode 112. Path Sum
- Leetcode-112. Path Sum
- 第六周:[Leetcode]112. Path Sum
- 【一天一道LeetCode】#112. Path Sum
- leetcode - 112. Path Sum
- [Leetcode] 112. Path Sum