leetcode刷题,总结,记录,备忘 112
2015-10-25 15:59
369 查看
leetcode112Path Sum
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
return true, as there exist a root-to-leaf path
使用递归,只有在叶节点的时候才真正的计算是否相等,然后将结果返回出去,其余父节点处只需得到2个分支的结果的或结果即可。
/**
* 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 Has(TreeNode * root, int sum, int result)
{
if (root == NULL)
{
return false;
}
if (root->left == NULL && root->right == NULL)
{
return root->val + result == sum;
}
return Has(root->left, sum, result + root->val) || Has(root->right, sum, result + root->val);
}
bool hasPathSum(TreeNode* root, int sum) {
return Has(root, sum, 0);
}
};
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->2which sum is 22.
使用递归,只有在叶节点的时候才真正的计算是否相等,然后将结果返回出去,其余父节点处只需得到2个分支的结果的或结果即可。
/**
* 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 Has(TreeNode * root, int sum, int result)
{
if (root == NULL)
{
return false;
}
if (root->left == NULL && root->right == NULL)
{
return root->val + result == sum;
}
return Has(root->left, sum, result + root->val) || Has(root->right, sum, result + root->val);
}
bool hasPathSum(TreeNode* root, int sum) {
return Has(root, sum, 0);
}
};
相关文章推荐
- nmap端口查看工具
- 杭电1202--学分
- Linux netfilter 学习笔记 之二 ip 层netfilter的hook 注册以及执行hook函数的概要分析
- 关于"短信处理"模式的一段讨论
- POJ 1125 Stockbroker Grapevine (Floyd)
- Python标准库:内置函数hasattr(object, name)
- android应用界面主题Theme使用方法
- HDU 1695 GCD(欧拉函数+容斥原理)
- 杭电1205--吃糖
- js document对象
- HTML学习7:常用标签之表格标签
- 我胡汉三又回来了
- 黑马程序员——OC语言日志——NSArray的介绍和使用
- Linux netfilter 学习笔记 之六 ip层netfilter的filter表的创建及其hook函数分析
- spring 入门级程序示例
- 修改mysql编码为UTF-8
- OC面向对象特性:封装
- javascript基本语法6 其他引用类型对象
- WampServer 2.5 如何实现局域网访问?
- uva11234