二叉树中和为某一值的路径
来源:互联网 发布:win10不能下载软件 编辑:程序博客网 时间:2024/06/08 00:20
题目:对于一个给定的二叉树,再给定一个数值,在该二叉树中找出和为该数值的路径(所有路径)。
代码如下:
package problem2;import java.util.Iterator;import java.util.LinkedList;/** * @author Hutongling * * @time:2017年3月21日 下午4:14:50 */public class 二叉树中和为某一值的路径 { private static void findPath(TreeNode root, int expectedSum){ if(root==null) return; LinkedList<Integer> path=new LinkedList<Integer>(); int currentSum=0; findPath(root, expectedSum,path,currentSum); } private static void findPath(TreeNode root, int expectedSum, LinkedList<Integer> path, int currentSum) { currentSum+=root.getValue(); path.push(root.getValue()); boolean isLeaf=(root.getLeftChild()==null && root.getRightChild()==null); if(currentSum==expectedSum && isLeaf){ System.out.println("A path is found:");// Iterator<Integer> iter=path.iterator();// while(iter.hasNext())// System.out.print(iter.next() + " "); Object[] arrayList=path.toArray(); for(int i=arrayList.length-1;i>=0;i--) System.out.print(arrayList[i] + " "); System.out.println(); } if(root.getLeftChild()!=null) findPath(root.getLeftChild(), expectedSum, path, currentSum); if(root.getRightChild()!=null) findPath(root.getRightChild(), expectedSum, path, currentSum); currentSum-=root.getValue(); path.pop(); } public static void main(String[] args) { TreeNode root=new TreeNode(10); TreeNode RLeft=new TreeNode(5); TreeNode RRight=new TreeNode(12); TreeNode RLLeft=new TreeNode(4); TreeNode RLRight=new TreeNode(7); root.setLeftChild(RLeft); root.setRightChild(RRight); RLeft.setLeftChild(RLLeft); RLeft.setRightChild(RLRight); findPath(root, 22); }}
结果如下:
A path is found:
10 5 7
A path is found:
10 12
0 0
- 【树】二叉树中和为某一值的路径
- 【树6】二叉树中和为某一值的路径
- 题目11:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的所有路径
- 题目1368:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 1368:二叉树中和为某一值的路径 @jobdu
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- Q25:二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径(剑指offer25)
- 网格变形动画
- 数组的循环移动
- 使用DrawerLayout实现侧拉菜单
- 关于plsql的commit,事务回滚 rollback
- VC++ 通过ADO连接数据库查询时返回空值报错的解决方案
- 二叉树中和为某一值的路径
- Android自带的倒计时CountDownTimer
- HTML 提高页面加载速度的方法
- TP3.2的URL重写省略index.php问题
- 机器学习实战---读书笔记: 第3章 决策树
- [Weex-BBQ]Weex项目中引用css样式的三种姿势
- Oracle中查看所有表和字段以及表注释.字段注释
- s标签大全
- Android5.0之NavigationView的使用