题意:输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径(一直到叶节点)。
思路:分别用栈和ArrayList实现了。
代码:
package MianShiTi_25;
import java.awt.FontFormatException;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Stack;
public class MianShiTi_25 {
public static class binaryTree {
int value;
binaryTree left;
binaryTree right;
}
//ArrayList实现
public void printPaths(binaryTree pNode , int value ,int currentSum , ArrayList<Integer> list ) {
if(pNode == null){
System.out.println("error");
}
if(pNode.value == value){
System.out.println(pNode.value);
}
if(pNode != null){
list.add(pNode.value);
currentSum += pNode.value;
boolean isLeaf = pNode.left ==null && pNode.right ==null;
if(currentSum < value ){
if(pNode.left != null){
printPaths(pNode.left, value, currentSum , list);
}
if(pNode.right != null){
printPaths(pNode.right, value, currentSum , list);
}
}
else if(currentSum == value){
if(isLeaf){
System.out.println(list.size());
System.out.println(list);
}
}
list.remove(list.size()-1);
}
}
//栈实现
public void printPaths_2(binaryTree root , int value , int currentSum , Stack<binaryTree> stack) throws Exception {
if(root == null || value <0){
throw new Exception("error implemation");
}
if(root != null){
stack.push(root);
currentSum +=root.value;
boolean isLeaf = root.left == null && root.right == null;
if(currentSum < value){
if(root.left != null){
printPaths_2(root.left, value, currentSum, stack);
}
if(root.right != null){
printPaths_2(root.right, value, currentSum, stack);
}
}
else if(currentSum == value){
if(isLeaf){
printStack(stack);
System.out.println();
}
}
}
stack.pop();
}
public static void printStack(Stack<binaryTree>stack) {
for (binaryTree binaryTree : stack) {
System.out.print(binaryTree.value+" ");
}
}
public static void main(String[] args) throws Exception {
int value = 22;
binaryTree node = new binaryTree();
node.value = 10;
node.left = new binaryTree();
node.left.value = 5;
node.right = new binaryTree();
node.right.value = 12;
node.left.left = new binaryTree();
node.left.left.value = 4;
node.left.right = new binaryTree();
node.left.right.value = 7;
int currentSum = 0;
MianShiTi_25 test = new MianShiTi_25();
ArrayList<Integer>list = new ArrayList<>();
//test.printPaths(node, 22, currentSum , list);
Stack<binaryTree>stack = new Stack<>();
test.printPaths_2(node, 22, 0, stack);
}
}