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

  

[LeetCode] 112. Path Sum 路径和的更多相关文章

  1. [leetcode]112. Path Sum路径和(是否有路径)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  2. LeetCode 112. Path Sum路径总和 (C++)

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  3. leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III

    112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root ...

  4. [LeetCode] 112. Path Sum 二叉树的路径和

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  5. [LeetCode] 112. Path Sum ☆(二叉树是否有一条路径的sum等于给定的数)

    Path Sum leetcode java 描述 Given a binary tree and a sum, determine if the tree has a root-to-leaf pa ...

  6. LeetCode 112. Path Sum (二叉树路径之和)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  7. LeetCode 112. Path Sum 二叉树的路径和 C++

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  8. LeetCode 112 Path Sum(路径和)(BT、DP)(*)

    翻译 给定一个二叉树root和一个和sum, 决定这个树是否存在一条从根到叶子的路径使得沿路全部节点的和等于给定的sum. 比如: 给定例如以下二叉树和sum=22. 5 / \ 4 8 / / \ ...

  9. LeetCode 112. Path Sum(路径和是否可为sum)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

随机推荐

  1. 小白式Git使用教程,从0到1

    Git是什么? Git是目前世界上最先进的分布式版本控制系统.工作原理 / 流程: Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remo ...

  2. 利用SQL直接生成模型实体类

    在网上找来一个别人写好的,生成实体类的SQL代码 declare @TableName sysname = 'lkxxb' declare @Result varchar(max) = 'public ...

  3. P1197 [JSOI2008]星球大战[并查集+图论]

    题目来源:洛谷 题目描述 很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武器统治着整个星系. 某一天,凭着一个偶然的机遇,一支反抗军摧毁了帝国的超级武器,并攻下了星系中几乎所有的星球.这些星球 ...

  4. jpa之No property buyerOpenId found for type OrderMaster! Did you mean 'buyerOpenid'?

    java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.conte ...

  5. 项目(一)--python3--爬虫实战

    最近看了python3网络爬虫开发实战一书,内容全面,但不够深入:是入门的好书. 作者的gitbook电子版(缺少最后几章) python3网络爬虫实战完整版PDF(如百度网盘链接被屏蔽请联系我更新) ...

  6. python开发笔记-如何做数据准备

    时间格式: >>> from datetime import date >>> firstday = date.fromtimestamp(1464010200) ...

  7. SOLOR介绍

    https://www.cnblogs.com/ki16/p/11209508.html

  8. po模式

    一条测试用例可能需要多个步骤操作元素,将每一个步骤单独封装成一个方法,在执行测试用例时调用封装好的方法进行操作.PO模式可以把一个页面分为三个层级,对象库层.操作层.业务层. 对象库层:封装定位元素的 ...

  9. LeetCode 1004. Max Consecutive Ones III

    原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-iii/ 题目: Given an array A of 0s and 1s, w ...

  10. LeetCode 958. Check Completeness of a Binary Tree

    原题链接在这里:https://leetcode.com/problems/check-completeness-of-a-binary-tree/ 题目: Given a binary tree, ...