leetcode:Path Sum 【Java】
2016-03-07 17:30
501 查看
一、问题描述
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
return true, as there exist a root-to-leaf path
二、问题分析
利用递归思想。
三、算法代码
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->2which sum is 22.
二、问题分析
利用递归思想。
三、算法代码
/** * 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 (root.left == null && root.right == null){ // leaf return sum == root.val; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
相关文章推荐
- java加密解密___MD5的简单使用
- Java IO流详尽解析
- 关于JAVA面向对象基础整理以及个人的理解(适合初学者阅读)
- Installing the Eclipse Plugin
- 深入剖析Java中的装箱和拆箱
- 路由器扫描的Java源码
- 初步尝试在Eclipse 中运行LeakCannary展现程序内存溢出
- .Jsp 在页面浏览时弹出 未提供相应的服务,请检查Spring 配置文件
- java 用org.quartz.Scheduler 包写动态调度任务
- spring框架的XML扩展特性:让spring加载和解析你自定义的XML文件
- java 反射机制详解
- eclipse 中git解决冲突
- JAVA与AS2制作一个2D多人游戏(1)
- eclipse 快捷键
- 集合竞价 CCF java实现 (大部分代码是借鉴的别人的,)
- [疯狂Java]AWT:菜单栏、菜单、菜单项、菜单事件处理
- 【Java开发者自学笔记】Java SE 笔记1
- java 判断日期相差几天
- Spring 并发访问的线程安全性问题
- Maven+Spring+Mybatis+Security+Mysql简短的框架