leetcode--Path Sum
2015-06-05 16:49
429 查看
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
分类:二叉树
题意:在二叉树中查找和为sum的路径(从根节点到叶子节点)
解法1:递归。由于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.
分类:二叉树
题意:在二叉树中查找和为sum的路径(从根节点到叶子节点)
解法1:递归。由于sum可能是负数,所以必须遍历到根节点,过程中不能剪枝。
/** * 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.val==sum &&root.left==null&&root.right==null){ return true; }else{ return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val); } } }
相关文章推荐
- __try,__except,__finally,__leave异常模型机制
- iOS开发多线程篇—NSOperation基本操作
- ios8 xcode设置launchimage
- BZOJ 2021 Usaco2010 Jan Cheese Towers 动态规划
- Linux socket文件传输2
- 5.1.10 Populating Next Right Pointers in Each Node II
- Java for LeetCode 154 Find Minimum in Rotated Sorted Array II
- wamp使用方法【总】
- JAVA数据结构系列 栈
- Linux SSH远程文件/目录传输命令scp
- Android利用canvas画各种图形(点、直线、弧、圆、椭圆、文字、矩形、多边形、曲线、圆角矩形)
- 初学单向链表中的头结点与头指针
- iOS开发多线程篇—NSOperation简单介绍
- iOS之数据请求NSURLConnection
- 装饰者模式及C++ 2
- dubbo2.5.3 dubbo:application
- showModalDialog chrome 新版本解决方案
- Action中访问Servlet API
- 九度1005
- c# 文件同步服务器,iis 集群 ,代码同步(二)