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,问是否有一个从根到叶节点的路径,使得路径上所有的值加起来等于给定的sum。

解法:最基本的深度优先搜索DFS(Depth-First Search),从根节点出发,搜索每一个到叶节点的路径,然后判断和是否为sum。

Java:

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode (int x) { val = x; } } class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null & root.right == null & sum == root.val) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.left.right = new TreeNode(2);
Solution sol = new Solution();
System.out.println(sol.hasPathSum(root, 22));
}
}  

Python:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None:
return False if root.left is None and root.right is None and root.val == sum:
return True return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

C++:

/**
* Definition for binary tree
* 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;
if (root->left == NULL && root->right == NULL && root->val == sum ) return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};

  

类似题目:

[LeetCode] 257. Binary Tree Paths 二叉树路径

[LeetCode] 113. Path Sum II 路径和 II

[LeetCode] 437. Path Sum III 路径和 III

  

最新文章

  1. 通过网页的JS代码启动移动APP
  2. 验证码 mewebstudio/captcha
  3. 如何在ecshop订单中显示客户给商家的留言
  4. groupadd命令详解(实例)
  5. 图片上传前的预览(PHP)
  6. IOC知识
  7. Golang学习 - path/filepath 包
  8. .Net课程体系
  9. NOIP2002 字串变换
  10. zepto源码研究 - zepto.js-4(常用的工具)
  11. linux 下 tomcat 之 配置静态资源路径
  12. 编程那些事儿:如何快速地"借用"CSS
  13. 【BZOJ1076】奖励关(动态规划,数学期望)
  14. Ubuntu 14.04 结束支持该如何应对?
  15. 2017-2018-2 20155228 《网络对抗技术》 实验八:Web基础
  16. 如何优雅的选择字体(font-family)
  17. javascript调用Flash里对象的方法(函数)搞了五个小时。
  18. Hadoop环境搭建及wordcount程序
  19. mysql 备份脚本
  20. 打印pdf

热门文章

  1. ViCANdo新版本发布(PART2)| XCP集成
  2. ADAS 实车道路及场地测试服务
  3. 18、DKN(Deep Knowledge-Aware Network for News Recommendation)---新闻推荐
  4. 学习Microsoft Visio(3)
  5. 日期对象|Date构造函数|
  6. C语言 define实现的宏函数汇总
  7. How to change hostname on debian
  8. 开源项目 12 ServiceStack.OrmLite
  9. (转)React事件处理函数必须使用bind(this)的原因
  10. x32下的DLL隐藏