import java.util.Iterator;
import java.util.LinkedList;
public class E34FindPathDependOnSum {
//二叉树中和为某一值的路径
private static class BinaryTreeNode{
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
public static void findPath(BinaryTreeNode root, int expectedSum){
if (root == null)
return;
LinkedList<BinaryTreeNode> stack = new LinkedList<>();
findPathCore(root, expectedSum, stack, 0);
}
private static void findPathCore(BinaryTreeNode root, int expectedSum,
LinkedList<BinaryTreeNode> stack, int currentSum){
//入栈
currentSum += root.value;
stack.push(root);
//满足条件(值相等且为叶子节点)则打印
if (currentSum == expectedSum && root.left == null && root.right == null){
Iterator<BinaryTreeNode> iterator = stack.descendingIterator();
System.out.print("Find a path: ");
while(iterator.hasNext()){
System.out.printf("%d ", iterator.next().value);
}
System.out.print("\n");
}
//否则继续寻找
if (root.left != null){
findPathCore(root.left, expectedSum, stack, currentSum);
}
if (root.right != null){
findPathCore(root.right, expectedSum, stack, currentSum);
}
//出栈
stack.pop();
}
//根据从上到下从左至右的二叉树遍历序列重构二叉树,用于测试
private static BinaryTreeNode construct(int[] order, int index){
if (index >= order.length)
return null;
BinaryTreeNode node = new BinaryTreeNode();
node.value = order[index];
node.left = construct(order, index * 2 + 1);
node.right = construct(order, index * 2 + 2);
return node;
}
//测试用例
public static void main(String[] args){
int[] binarySearchTree = {10, 5, 12, 4, 7};
BinaryTreeNode root = construct(binarySearchTree, 0);
E34FindPathDependOnSum.findPath(root, 22);
/*result:
* Find a path: 10 5 7
* Find a path: 10 12
*/
}
}
二叉搜索树中和为某一值的路径(Java实现)
最新推荐文章于 2021-11-16 12:21:27 发布