LeetCode[Tree]: Path Sum
来源:互联网 发布:0 1背包分支界限算法 编辑:程序博客网 时间:2024/05/17 11:05
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 andsum = 22
,
return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
这个题目非常适合用递归来做,C++代码实现非常简单:
bool hasPathSum(TreeNode *root, int sum) { if (!root) return false; if (root->left && hasPathSum(root->left, sum - root->val)) return true; if (root->right && hasPathSum(root->right, sum - root->val)) return true; if (root->left == nullptr && root->right == nullptr && root->val == sum) return true; return false; }
时间性能如下图所示:
0 0
- LeetCode[Tree]: Path Sum
- **(leetcode) (tree) Path Sum II
- LeetCode[Tree]: Path Sum II
- [leetcode][tree][dfs] Path Sum
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- 逃不掉的双十一 可怕的分布式架构隐患
- robotframe及ride 源码解析(一) 动态调用关键字-Library keywords
- 多线程之Runnable,Callable,Future,FutureTask
- Java异常处理,SimpleDateFormat中的parse函数操作
- maven的profile设置
- LeetCode[Tree]: Path Sum
- IOS学习笔记 第2篇 OC面向对象(二)
- USACO4.1.1 Beef McNuggets (nuggets)
- MTK_SDK 相关问题整理
- POJ 3237 Tree (树链剖分+线段树)
- (5086)HDU
- 【hibernate框架】关系映射之一对一单项外键关联(Annotation实现)
- Palindrome Partitioning II
- LeetCode Longest Substring Without Repeating Characters