[Leetcode] Path Sum
2014-03-31 01:08
190 查看
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
水!
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.
水!
/** * 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; } bool flag1 = hasPathSum(root->left, sum - root->val); bool flag2 = hasPathSum(root->right, sum - root->val); return flag1 || flag2; } };
相关文章推荐
- C++的一些知识点汇总
- 黑马程序员_2_TreeSet集合Jdk1.7小知识
- Mental ray 的建筑渲染Arch&Design材质
- 浅谈泛型编程
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- properties文件中文乱码解决
- Mental ray 渲染器常用设置
- unity3d中让某个物体透明
- Hibernate概述和增删改查入门
- 第四周作业1
- win7下安装vs2008失败——解决方法
- Google Chrome Error code:ERR_UNSAFE_PORT
- HibernateTemplate 详解
- [Leetcode] Multiply Strings
- J2EE Web开发环境的搭建!!
- MyReport数据导出引擎——MyReport的好帮手,支持Excel导出
- string类型在参数传递中如何作为引用,如何在函数外修改函数内的string类型
- 洗牌算法shuffle
- Commons DbUtis源码阅读四
- Android Alarm