《leetCode》:Path Sum
2016-02-26 15:12
369 查看
题目
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.
思路
思路:判断该节点是否为叶子节点,如果是叶子节点,则判断该节点的val是否与sum相等,如果不是叶子节点,则判断该节点的左右子树中是否存在路径的和等于(sum-root->val);实现代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool hasPathSum(struct TreeNode* root, int sum) { //有效性检查 if(root==NULL){ return false; } if(root->left==NULL&&root->right==NULL){//到达叶子节点,判断是否等于sum if(root->val==sum){ return true; } else{ return false; } } else{ return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); } }
相关文章推荐
- ELK日志分析系统-Logstack
- python语言特性(四)
- Unity5.3 JSON的序列化
- Android如何获取系统高度、标题栏和状态栏高度
- tomcat修改控制台日志输出到文件的解决办法__http://wenku.baidu.com/link?url=inKWTkePOVaNcN9o07BGiiOgHaQefnUAhXfj9Bmn-BX
- OC初级基础语法与内存管理MRC
- Block-----镜像拷贝
- SVN连接不上
- PowerDesigner使用教程
- git实践
- 什么是真正的程序员?
- CSDN-markdown编辑器说明
- 在网页中添加新浪微博“加关注”按钮
- getrlimit、setrlimit
- 自己动手写处理器之第四阶段(1)——第一条指令ori的实现
- Nginx源码结构
- iOS图片压缩
- mysql存储过程参数比较
- 面试题之一过桥问题
- kali下建造类似wifi pineapple的AP