剑指Offer 25题 二叉树中和为某一值的路径 Java
来源:互联网 发布:淘宝如何清空收藏夹 编辑:程序博客网 时间:2024/06/14 18:59
对二叉树的相关算法还是不了解。
这里有两点是之前所用不好的:
1:把栈用进来;
2:有一个变量记录当前的数值,这个在递归的过程当中就能够得到之前的值。
package test;import java.util.Stack;public class FindPath {class BinaryTreeNode{int value;BinaryTreeNode left;BinaryTreeNode right;}public void findPath(BinaryTreeNode root, int expectedSum){if(root == null)return;Stack<BinaryTreeNode> stackPath = new Stack<>();int currentSum = 0;findPath(root, expectedSum, stackPath, currentSum);}public void findPath(BinaryTreeNode root, int expectedSum, Stack<BinaryTreeNode> path, int currentSum){currentSum += root.value;path.push(root);boolean isLeaf = root.left ==null && root.right == null;if(currentSum == expectedSum && isLeaf){System.out.println("A path is found: ");for(BinaryTreeNode node: path){System.out.print(node.value +" ");}System.out.println();}if(root.left != null)findPath(root.left, expectedSum, path, currentSum);if(root.right !=null)findPath(root.right, expectedSum, path, currentSum);path.pop();}public static void main(String[] args) {// TODO Auto-generated method stubFindPath findPath = new FindPath();BinaryTreeNode binaryTreeNode10 = findPath.new BinaryTreeNode();binaryTreeNode10.value = 10;BinaryTreeNode binaryTreeNode5 = findPath.new BinaryTreeNode();binaryTreeNode5.value = 5;BinaryTreeNode binaryTreeNode12 = findPath.new BinaryTreeNode();binaryTreeNode12.value = 12;BinaryTreeNode binaryTreeNode4 = findPath.new BinaryTreeNode();binaryTreeNode4.value = 4;BinaryTreeNode binaryTreeNode7 = findPath.new BinaryTreeNode();binaryTreeNode7.value = 7;binaryTreeNode10.left = binaryTreeNode5;binaryTreeNode10.right = binaryTreeNode12;binaryTreeNode5.left = binaryTreeNode4;binaryTreeNode5.right = binaryTreeNode7;findPath.findPath(binaryTreeNode10, 22);}}
0 0
- 剑指Offer 25题 二叉树中和为某一值的路径 Java
- 剑指offer--面试题25:二叉树中和为某一值的路径--Java实现
- 剑指Offer面试题25(Java版):二叉树中和为某一值的路径
- 【剑指offer-Java版】25二叉树中和为某一值的路径
- 剑指Offer面试题25(Java版):二叉树中和为某一值的路径
- 剑指offer 面试题25 二叉树中和为某一值的路径-Java实现
- 剑指offer:二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值的路径
- 剑指offer--二叉树中和为某一值的路径
- 《剑指offer》二叉树中和为某一值的路径
- 【剑指Offer】二叉树中和为某一值的路径
- 剑指Offer--二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- [剑指offer]二叉树中和为某一值的路径
- 《剑指offer》-二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- notepad++ key words 设置
- Uva1451 数形结合
- solve 方法总结
- DIV与前面的控件在同一行显示.
- 手把手教你如何安装和使用Karma-Jasmine
- 剑指Offer 25题 二叉树中和为某一值的路径 Java
- C++获取当前路径
- 常用的项目管理工具JIRA | ...
- Leetcode 341. Flatten Nested List Iterator
- Python.微信
- C++创建文件夹
- 关于Windows用Task Scheduling执行C++ exe文件
- 10.Doctrine2 (2)
- Leetcode 215. Kth Largest Element in an Array