LeetCode Path Sum
来源:互联网 发布:乐当家软件 编辑:程序博客网 时间:2024/06/01 10:11
题目
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即可。
代码
/** * 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&&sum-root->val==0)//到达叶节点,且符合要求return true;if(hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val))//递归return true;return false; }};
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
- Tomcat 系统架构与设计模式
- HDOJ 2084 数塔
- Sublime2 注册码
- handler机制基础应用
- Android中asset文件夹和raw文件夹区别
- LeetCode Path Sum
- Java核心技术——集合
- vim 命令合集
- 【myeclipse】注释模板修改
- 初学 Java Web 开发,请远离各种框架,从 Servlet 开发
- 常用的Java代码汇总
- Linux java环境变量设置
- maven项目添加本地jar
- Unified Emoji表情for Android