[LeetCode] Path Sum
来源:互联网 发布:义乌美工 编辑:程序博客网 时间:2024/06/10 19:21
题目:
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 binary tree * 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) { return (root -> val == sum); } 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
- Linux系统各个目录的作用
- item1:使用静态工厂方法代替构造函数
- 【图像处理】OpenCV函数threshold的使用
- 数据结构+算法系列二: 所有知识点的梳理(持续更新中)
- javax.naming.NoInitialContextException: Need to specify class name in environment or system property
- [LeetCode] Path Sum
- ajax——XMLHttpRequest
- 记录1
- Linux /dev目录详解
- 总线
- 关于java作用域(public,private,protected,default)
- 电话号码转对于英文单词 --编程之美 (递归与非递归版)
- 清除浮动的各种方法总结
- redis(二)Redis适用场景,如何正确的使用