Path Sum--路径和(重)
来源:互联网 发布:淘宝可以用什么支付 编辑:程序博客网 时间:2024/04/30 22:23
问题:链接
Given the below binary tree and
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.
解答:
DFS或者BFS。同时,当本节点是叶子节点才判断和,否则节点为空时返回false
参考:http://www.cnblogs.com/remlostime/archive/2012/11/13/2767746.html
代码:
class Solution {public: bool hasPathSum(TreeNode *root, int sum) {return DFS(root, 0, sum); }bool DFS(TreeNode *root, int sum, int target){if(root == NULL)return false;if(root->left == NULL && root->right == NULL)return (target == sum + root->val);return DFS(root->left, sum+root->val, target) || DFS(root->right, sum+root->val, target);}};
0 0
- Path Sum--路径和(重)
- Path Sum II --路径和(重)
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- Path Sum 二叉树路径和 @LeetCode
- LeetCode Path Sum II路径和II
- Path Sum II 路径和II
- Minimum Path Sum 最小路径和
- [leetcode]Minimum Path Sum 最小路径和
- Leetcode:Minimum Path Sum 最小路径和
- LeetCode | Path Sum(路径和)
- LinCode Minimum Path Sum 最小路径和
- leetcode64-Minimum Path Sum(最小路径和)
- LeetCode 112. Path Sum(路径和)
- lintcode minimum-path-sum 最小路径和
- 最小路径和—Minimum Path Sum
- LeetCode-112-Path Sum(路径和)
- 黑马程序员_网络编程
- Java:重写equals()和hashCode()
- 为什么是Createthread后要CloseHandle
- VBA清除Excel密码保护,2003/2007/2010均适用
- C\C++小知识:C\C++中#define和inline的区别
- Path Sum--路径和(重)
- Java 中 再一次看单例模式
- ios返回当前时间,精确到毫秒。
- 黑马程序员_java中IO流的操作规律
- C++调用lua函数的一种通用办法
- servlet、genericservlet、httpservlet之间的区别
- Android中Activity、Service和线程之间的通信
- DFS IDFS 离散傅里叶级数
- POJ2876——递归