剑指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
原创粉丝点击