博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 112. Path Sum (二叉树路径之和)
阅读量:4623 次
发布时间:2019-06-09

本文共 1526 字,大约阅读时间需要 5 分钟。

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.

 


题目标签:Tree

  这道题目给了我们一个二叉树和一个sum, 让我们判断这个二叉树是否有至少一条path 的之和是等于sum的。利用preOrder 来遍历树,每次用sum 减去当前点的值,每当遇到一个leaf node 的时候检查sum 是不是等于0, 返回ture 和false。利用 || 来return 所有的boolean 值, 至少有过一个true,一个path之和等于sum, 总的boolean 就是true。

 

Java Solution:

Runtime beats 13.93% 

完成日期:07/03/2017

关键词:Tree

关键点:当是leaf node 的时候检查sum;利用 || return两个children的返回值

 

 

1 /** 2  * Definition for a binary tree node. 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution 11 {12     public boolean hasPathSum(TreeNode root, int sum) 13     {14         if(root == null)15             return false;16         17         sum -= root.val;18         19         if(root.left == null && root.right == null)20         {21             if(sum == 0)22                 return true;23             else 24                 return false;25         }26         27         return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);28     }29 }

参考资料:

http://www.cnblogs.com/springfor/p/3879825.html

 

LeetCode 算法题目列表 - 

转载于:https://www.cnblogs.com/jimmycheng/p/7114684.html

你可能感兴趣的文章
图像处理——图像平滑
查看>>
bean之间的属性是怎么维护的
查看>>
安卓开发笔记——打造属于自己的博客园APP(二)
查看>>
[读书笔记] 代码整洁之道(四): 类
查看>>
网络编程书籍
查看>>
html的base标签
查看>>
「luogu2766」最长不下降子序列问题
查看>>
logback.xml 配置使用
查看>>
iOS沙盒路径变化的说明详解
查看>>
MVC增加Areas,避免控制器冲突
查看>>
Unable to load template file 'rj\ThinkPHP/Tpl/dispatch_jump.tpl'----thinkphp3.2.3
查看>>
Javascript Date类常用方法详解
查看>>
IIS配置域用户自动登录
查看>>
linux基础命令
查看>>
Java——Json字符串与Object互转
查看>>
Guava官方文档-RateLimiter类
查看>>
css2----清除浮动
查看>>
为HTML添加图片登录按钮
查看>>
Vuejs模板绑定
查看>>
Archlinux/Manjaro使用笔记-报错:一个或多个 PGP 签名无法校验!的解决方法
查看>>