LeetCode[Tree]: Path Sum
2015-02-03 19:19
330 查看
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
![](http://img.blog.csdn.net/20150203191737482?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hmZTAwNw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
return true, as there exist a root-to-leaf path
这个题目非常适合用递归来做,C++代码实现非常简单:
时间性能如下图所示:
For example:
Given the below binary tree and
sum = 22,
return true, as there exist a root-to-leaf path
5->4->11->2which 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; }
时间性能如下图所示:
相关文章推荐
- [leetcode][tree][dfs] Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- Leetcode: mimimum depth of tree, path sum, path sum II
- 【Leetcode】Construct binary tree from inorder and postorder traversal
- [Leetcode] #109 Convert Sorted List to Binary Search Tree
- Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
- Binary Tree Postorder Traversal --leetcode
- LeetCode-105. Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Level Order Traversal II - LeetCode
- LeetCode_maximum-depth-of-binary-tree
- LeetCode力扣之108. Convert Sorted Array to Binary Search Tree
- LeetCode: Invert Binary Tree
- 【leetcode】Array——Construct Binary Tree from Preorder and Inorder Traversal(105)
- LeetCode Validate Binary Search Tree
- 【leetcode】Binary Tree Inorder Traversal
- leetCode(14):Invert Binary Tree and Same Tree 分类: leetCode 2015-06-21 11:48 170人阅读 评论(0) 收藏
- [leetcode] Binary Tree Right Side View
- LeetCode Binary Tree Inorder Traversal
- Leetcode 树 Binary Tree Postorder Traversal