leetcode No112. Path Sum
来源:互联网 发布:女人出轨 知乎 编辑:程序博客网 时间:2024/05/17 03:09
Question:
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.
判断是否有路径和等于sum
Algorithm:
DFS
Accepted Code:
/** * 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; else if(root->val==sum&&root->left==NULL&&root->right==NULL) return true; bool b1=false; bool b2=false; int curVal=root->val; b1=hasPathSum(root->left,sum-curVal); b2=hasPathSum(root->right,sum-curVal); return b1||b2; }};
0 0
- leetcode No112. Path Sum
- 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
- POJ-1039-Pipe
- Error:Execution failed for task ':app:mergeDebugResources'. 报错
- eclipse官网下载地址
- spring boot日志—logback
- 【原创】【OpenJudge】 1792:迷宫
- leetcode No112. Path Sum
- 数据结构实验之查找六:顺序查找
- 【AndroidStudio】关于SVN的相关配置简介
- 6自真经出需求 - 产品经理必须看
- Linux学前硬件电路(二)1
- 全文检索
- androidStudio出现Executing tasks: [:app:assembleDebug]等错误不能运行程序
- 文章观点提取的几种测试
- 机器学习(周志华)习题解答1.1-1.3: 理解假设和版本空间