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 andsum =
2016-05-20 11:33
585 查看
Givenabinarytreeandasum,determineifthetreehasaroot-to-leaf
pathsuchthataddingupallthevaluesalongthepathequalsthegiven
sum.
Forexample:
Giventhebelowbinarytreeandsum=22,
returntrue,asthereexistaroot-to-leafpath5->4->11->2whichsumis22.
代码1
pathsuchthataddingupallthevaluesalongthepathequalsthegiven
sum.
Forexample:
Giventhebelowbinarytreeandsum=22,
5 /\ 48 //\ 11134 /\\ 721
returntrue,asthereexistaroot-to-leafpath5->4->11->2whichsumis22.
代码1
importjava.util.ArrayList; classTreeNode{ intval; TreeNodeleft; TreeNoderight; TreeNode(intx){val=x;} } publicclassSolution{ ArrayList<ArrayList<Integer>>result=newArrayList<ArrayList<Integer>>(); ArrayList<Integer>arr=newArrayList<Integer>(); publicbooleanhasPathSum(TreeNoderoot,intsum){ if(root==null)returnfalse; isPath(root,0,sum); if(result.isEmpty())returnfalse; elsereturntrue; } privatevoidisPath(TreeNoderoot,intsum,inttarget){ if(root==null)return; else{ sum+=root.val; arr.add(root.val); if(root.left==null&&root.right==null&&sum==target){ result.add(newArrayList<Integer>(arr)); } isPath(root.left,sum,target); isPath(root.right,sum,target); arr.remove(arr.size()-1); sum-=root.val; } } } 代码二:
importjava.util.ArrayList; classTreeNode{ intval; TreeNodeleft; TreeNoderight; TreeNode(intx){val=x;} } publicclassSolution{ publicbooleanhasPathSum(TreeNoderoot,intsum){ returnhasPathSumHelper(root,sum); } privatebooleanhasPathSumHelper(TreeNoderoot,intsum){ //TODOAuto-generatedmethodstub if(root==null)returnfalse; if(root.left==null&&root.right==null&&sum==root.val)returntrue; returnhasPathSumHelper(root.left,sum-root.val)||hasPathSumHelper(root.right,sum-root.val); } }
相关文章推荐
- Arduino入门教程—RFID模块的使用(MF RC522)
- MySQL: Starting MySQL….. ERROR! The server quit without updating PID file解决办法
- uisearchbar背景色
- WCF学习系列三--【WCF Interview Questions – Part 3 翻译系列】
- UITableViewCell 自适应高度
- topic 和queue的区别和应用 activeMQ
- UE 的文件比较方法
- UIImageResizingModeStretch聊天气泡的图片拉伸
- 类似于StringBuilder的字符串加强处理类
- Vickate_iOS_UILable自适应宽度/自适应高度
- j-query 中文乱码处理 单词 escape 及其他的中文乱码处理
- UITableViewCell分割线设置满屏
- 使用Liferay IDE 3.0创建支持Service Builder的portlet module
- DuiLib属性--使用html
- 万能启动的最后的传说:UD三分区法部署教程!UD加UEFI!
- UD三分区补充教程1——激活不同分区对于UD三分区bios启动和uefi启动兼容性影响的讨论
- 开启Query Cache导致的一个报错
- Request常用方法
- UICollectionView(一)——整体总结
- Vickate_iOS设置状态栏(UIStatusBar)的颜色两步走