package com.company;
import java.util.List;
import java.util.Stack;
public class FindSumTree {
static class BinaryTreeNode{
int value ;
BinaryTreeNode left = null;
BinaryTreeNode right = null;
public BinaryTreeNode(int value){
this.value = value;
}
}
public static void main(String[] args){
BinaryTreeNode node = new BinaryTreeNode(10);
BinaryTreeNode node2 = new BinaryTreeNode(5);
BinaryTreeNode node3 = new BinaryTreeNode(12);
BinaryTreeNode node4 = new BinaryTreeNode(4);
BinaryTreeNode node5 = new BinaryTreeNode(7);
BinaryTreeNode node6 = new BinaryTreeNode(3);
BinaryTreeNode node7 = new BinaryTreeNode(3);
node.left = node2;
node.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
printTreePath(node,22);
}
public static void printTreePath(BinaryTreeNode node ,int sum){
int currentSum = 0;
Stack<BinaryTreeNode> stack = new Stack<>();
if(node == null) {
System.out.print("node == null");
}
findPath(node, stack,sum,currentSum);
}
public static void findPath(BinaryTreeNode node ,Stack<BinaryTreeNode> stack, int sum , int currentSum){
if(node != null){
currentSum += node.value;
stack.push(node);
}
checkStackAndPrint(stack,sum);
if(node.left != null){
findPath(node.left,stack,sum,currentSum);
}
if(node.right != null){
findPath(node.right,stack,sum,currentSum);
}
if(!stack.isEmpty()){
stack.pop();
}
}
public static void checkStackAndPrint(Stack<BinaryTreeNode> stack, int sum){
int nodeSum = 0;
for(BinaryTreeNode temp : stack){
nodeSum += temp.value;
}
if(sum == nodeSum ){
System.out.println();
for(BinaryTreeNode node:stack){
System.out.print(" "+node.value);
}
}
}
}
每一层递归中不断保存数据,每一层递归结束后就删除数据,这样栈中就保存了每条路径的的数值,递归程之后,所有元素都出栈。