Leetcode 112 PathSum

题目链接: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 the values along the path equals the given sum.

Note: A leaf is a node with no children.

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.

解题思路

递归求解:

如果为叶子结点且值的和为目标 则返回ture,否则 递归左右子树,其中之一返回ture即可。

题解

    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        if(root.left==null && root.right==null && sum== root.val) return true;
        int temp = sum-root.val;
        
        return hasPathSum(root.left,temp) || hasPathSum(root.right,temp);
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 3,386评论 0 8
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,483评论 0 10
  • [[UIApplicationsharedApplication]setIdleTimerDisabled:YES];
    IRONYT阅读 147评论 0 0
  • 从这周开始学习区块链知识,一直在进行小数额的投资,这次开始投资区块链,在可控制金额与风险内,寻求更高的收益。 区块...
    Dr魏阅读 316评论 0 0
  • 中午,接到一个消息,在之前的想像中,应该是非常激动的一刻,可当时却貌似出奇的平静。 前年底开始,一直到去年底,前后...
    皮皮老猫阅读 129评论 2 2