Path Sum
来源:互联网 发布:网络授权书尺寸 编辑:程序博客网 时间:2024/05/16 10:59
原题
https://leetcode.com/problems/path-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 sum = 22,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
翻译:给一棵二叉树和一个数值,判断是否有一条从树根到叶节点的路径,使得该路径上的节点的值的和为这个给定值。
如图中,给定22,有 5->4->11->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 hasPathSum(TreeNode* root, int sum) { if(root == NULL) return false; return hasSum(root,sum,0); } bool hasSum(TreeNode* theRoot, int sum, int tempSum) { if(theRoot->left == NULL && theRoot->right == NULL) return theRoot->val + tempSum == sum; if(theRoot->left != NULL) { if(theRoot->right != NULL) return hasSum(theRoot->left,sum,tempSum + theRoot->val) || hasSum(theRoot->right,sum,tempSum + theRoot->val); else return hasSum(theRoot->left,sum,tempSum + theRoot->val); } else return hasSum(theRoot->right,sum,tempSum + theRoot->val); }};
0 0
- Path Sum && Path Sum ||
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- CS224d lecture 13札记
- thinkphp 更新数据时如果未修改数据,返回结果判断错误
- Android SDK 201508可用的镜像下载
- Dubbo架构设计详解
- 认证中心公钥(CA)与IC卡参数
- Path Sum
- CoreLocation(一)
- UI设计中的结构设计
- html5开发之viewport使用
- Java中的String类以及 == 和equals()方法的比较!
- android <xliff:g> 疑惑
- 包养包养枯干权顶替仍有仍
- 论交互式设计与用户的关系
- Regionals 2009 >> Asia - Hsinchu UVALIVE, 4528 Schedule Pairs of Jobs - 搜索回溯