Leetcode Path Sum
来源:互联网 发布:战舰世界新墨西哥数据 编辑:程序博客网 时间:2024/06/10 15:32
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.
代码如下:
/** * 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) { if(root == NULL) return false; int count = 0; return path(root,sum,count); } bool path(TreeNode* root,int sum,int count) { if(root == NULL) { return false; } count += root->val; if(root->left == NULL && root->right == NULL) return count == sum; return path(root->left,sum,count) || path(root->right,sum,count); }};
虽然求解出来了,但是觉得我的递归写的特别奇怪。一般递归解法应该是十分简洁的,对代码进行优化:
/** * 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) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL && root->val == sum) return true; return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val); }};
阅读全文
0 0
- leetcode Path Sum && Path Sum ||
- 【Leetcode】Path Sum (Sum)
- leetcode:leetcode :Path Sum
- 【Leetcode】Path Sum II (Sum)
- LeetCode: Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- LeetCode Minimum Path Sum
- LeetCode Path Sum
- LeetCode Path Sum II
- [Leetcode] Path Sum
- [Leetcode] Path Sum II
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- [LeetCode] Path Sum
- [LeetCode] Path Sum II
- JavaScript 事件绑定、事件监听、事件委托
- 查询所有表名
- 解决innerHTML包含的js代码不能被执行的问题
- Fasdfs 客户端 有没有提供资源池的必要
- Django-ORM进阶操作01
- Leetcode Path Sum
- 斯坦福大学推出对抗抑郁症的聊天机器人(附论文)
- C++远程DLL注入
- fps
- 关于SQLlite数据库 在32 位系统上的无法使用的问题
- JAVA的toString方法
- 大全
- jboss4.0遇到jstl.jar版本冲突错误
- 存储过程的简易使用