import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;
/**
* 二叉树中和为某一值的路径
* @author Administrator
*
*/
public class FindPath {
static void findPath(BinaryTree root,int expectedSum){
if(root==null)
return;
Vector<Integer> path = new Vector<Integer>();
int currentSum = 0;
findPath(root,expectedSum,path,currentSum);
}
private static void findPath(BinaryTree root, int expectedSum,
Vector<Integer> path, int currentSum) {
path.add(root.data);
currentSum += root.data;
boolean isLeaf = root.left==null&&root.right==null;
if(isLeaf&¤tSum==expectedSum){
System.out.println("find path:");
Iterator<Integer> it = path.iterator();
while (it.hasNext()) {
Integer integer = (Integer) it.next();
System.out.print(integer+" ");
}
}
if(root.left!=null)
findPath(root.left,expectedSum,path,currentSum);
if(root.right!=null)
findPath(root.right,expectedSum,path,currentSum);
path.remove(path.size()-1);
}
static BinaryTree createTree(){
Scanner sc = new Scanner(System.in);
int flag = sc.nextInt();
if(flag==0)
return null;
BinaryTree root = new BinaryTree(flag);
root.left = createTree();
root.right = createTree();
return root;
}
public static void main(String[] args) {
System.out.println("建立二叉树,输入0结束:");
BinaryTree root = createTree();
System.out.println("建立完毕");
findPath(root, 22);
}
}
class BinaryTree{
int data;
BinaryTree left;
BinaryTree right;
BinaryTree() {
}
BinaryTree(int data) {
this.data = data;
}
}
<img src="https://img-blog.csdn.net/20141107171322109" alt="" />