`

Path Sum

阅读更多
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,当遍历到一个节点时,从根节点到当前节点的和正好为sum,这时我们还要查看当前节点是否为叶子节点,如果为叶子节点就返回true,否则继续搜索。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        if(sum == root.val && root.left == null && root.right == null) return true;
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}
分享到:
评论

相关推荐

    LeetCode -- Path Sum III分析及实现方法

    主要介绍了LeetCode -- Path Sum III分析及实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

    LeetCode — Path Sum III分析及实现方法

    LeetCode — Path Sum III分析及实现方法 题目描述: You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need...

    【leetcode】【medium】113. Path Sum II

    113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree...

    cpp-算法精粹

    Binary Tree Maximum Path Sum Populating Next Right Pointers in Each Node Sum Root to Leaf Numbers LCA of Binary Tree 线段树 Range Sum Query - Mutable 排序 插入排序 Insertion Sort List 归并排序 Merge ...

    TWDH#Leetcode-From-Zero#07.路径总和1

    //将每一种可能性都放入set中,并依次与sum对比public int pathSum(TreeNode root, int mySum){//1.递归出口/

    javalruleetcode-LeetCode::lollipop:个人LeetCode习题解答仓库-多语言

    java lru leetcode :ice_cream: LeetCode Kindem 的个人 LeetCode 题解仓库,欢迎交流学习。 下面的目录中 $number 题号代表经典 LeetCode 题目,$number.$number 题号表示 ...Sum ...Sum ...Sum ...Path Sum 73

    sha1.exe, 计算,生成SHA1SUM或SHA1SUM.asc

    命令行工具. 计算SHA1SUM,生成SHA1SUM文件.校验SHA1SUM文件. 如果安装了GnuPG,并在PATH中,对SHA1SUM进行明文签名(生成SHA1SUM.asc)或对其验证.

    sha1.exe 1.0.2 计算,生成SHA1SUM或SHA1SUM.asc

    命令行工具. 计算SHA1SUM,生成SHA1SUM文件.校验SHA1SUM文件. 如果安装了GnuPG,并在PATH中,对SHA1SUM进行明文签名(生成SHA1SUM.asc)或对其验证. 修正对一些SHA1SUM.asc不能识别的bug

    leetcode分类-LeetCode:力码

    Path Sum Unique Paths Unique Paths II Longest Palindromic Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal Rectangle ###Recursion N-Queens N-...

    leetcode叫数-Leetcode_JS:leetcode编程题,javascript版本

    leetcode叫数 Leetcode_JS leetcode编程题,javascript版本 ##NO.35 Search Insert Position 这道题非常简单,数组是有序数组,只需要遍历一遍...Sum 这道题是关于二叉树的题,递归思路,也就是DFS的思路。 这里递归

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    Path Sum 2017/03/09 70.Climbing Stairs, 198.House Robber, 55.Jump Game 72.Edit Distance, 97.Interleaving String, 115.Distinct Subsequences 2017/04/24 (Lintcode)92.Backpack, (Lintcode)125.Backpack II, ...

    leetcode338-algorithm-training:leetcodecjava

    第 338 章力码解决方案 问题编号 标题 困难 C Java Ruby 338 中等的 [✓](/src/338 计数位/solution.c) 104 简单的 [✓](/src/104 二叉树的最大深度/solution.c) ...Path Sum II/solution.java) 258 简单的 [✓](/

    路径和:leet码问题的一种解决方案,用于查找树节点中是否存在给定的数字求和

    路径和解决leet码问题的方法,以查找树节点总和中是否存在给定的数字一个简单... 运行时间:4毫秒,比Path Sum的C ++在线提交的99.88%快。 内存使用:21.3 MB,少于Path Sum的C ++在线提交的96.61%。 德拉吉·吉达尔

    algorithm:通过hackerrank,codeforce,leetcode等练习练习编码。

    算法命令行界面设置样板来解决问题。 要使用CLI,请执行以下步骤cd bin/npm link用法al new [name] [arguments] 示例1... 示例2:带有参数al new path - sum node sum 输出var pathSum = function ( node , sum ) { } ;

    leetcodetreenode-binary-tree-maximum-path-sum:二叉树最大路径和

    leetcode 树节点二叉树最大路径和 ...max_sum = Integer . MIN_VALUE ; public int max_gain ( TreeNode node ) { if (node == null ) return 0 ; // max sum on the left and right sub-trees of node int lef

    多线程leetcode-leetcode-java:leetcode上的题解,基于java语言

    多线程 leetcode 前言 每天刷点leetcode,基于java语言...Path Sum II Copy List with Random Pointer Building H2O Fizz Buzz Multithreaded hard Merge k Sorted Lists Reverse Nodes in k-Group Trapping Rain Water

    Linux系统递归生成目录中文件的md5的方法

    linux下使用md5sum递归生成整个目录的md5 今天要用md5sum操作目录,递归生成目录下所有文件的md5值,结果发现它不支持递归操作于是写了个php脚本处理下 代码: <?php $path ='/data/www/bbs/source'; $...

    jsp结合javabean的实践

    hm.put("sum",new Double(sum_dingdan)); }catch (Exception e){ System.out.println(e.getMessage()); bl=false; //System.out.println("false"); } return hm; } public void setPath(String...

    text_sum

    训练模型:python3 ./run_seq2seq.py --model_name_or_path t5-base --do_train --do_eval -任务总结--train_file data / training_data.csv --validation_file data / testing_data.csv --output_dir ./tmp/tst-...

    Ruby遍历文件夹同时计算文件的md5sum

    #!/usr/bin/ruby -w # require 'digest/md5' ...def dir_md5sum(path) md5s=Array.new if File.directory?(path) Dir.new(path).each do |file| next if file =~ /^\.+$/ file=#{path}/#{file}

Global site tag (gtag.js) - Google Analytics