输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。
从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
import java.util.ArrayList;
class BinaryTree<T extends Comparable<T>>{
static class BinaryTreeNode<T>{
private T value;
private BinaryTreeNode<T> leftchild;
private BinaryTreeNode<T> rightchild;
public BinaryTreeNode(T value){
this.value=value;
leftchild=null;
rightchild=null;
}
}
public BinaryTreeNode<T> root=null;
public BinaryTree(T value){
root=new BinaryTreeNode<T>(value);
}
public void insert(BinaryTreeNode<T> node,T value){
if(node.value.compareTo(value)<=0){
if(node.leftchild ==null){
node.leftchild=new BinaryTreeNode<T>(value);
}
else
insert(node.leftchild,value);
}
else{
if(node.rightchild==null){
node.rightchild=new BinaryTreeNode<T>(value);
}
else
insert(node.rightchild,value);
}
}
public void inOrder(BinaryTreeNode<T> node){
if(node == null)
return;
inOrder(node.leftchild);
System.out.print(node.value+" ");
inOrder(node.rightchild);
}
private static int j=-1;
public BinaryTreeNode<T> createByPreOrderAndInOrder(T[] preOrder,T[] inOrder,int begin,int end){
if(preOrder==null || inOrder==null)
return null;;
/**根节点的值是前序遍历数组中下标为begin的值*/
j++;
if(j==preOrder.length)
return null;
T rootValue=preOrder[j];
BinaryTreeNode<T> root = new BinaryTreeNode<T>(rootValue);
/**在中序中找根节点*/
int i=0;
for(i=begin;i<end;i++){
if(inOrder[i].compareTo(rootValue)==0){
break;
}
}
/**构建左子树*/
if(begin+1<=i)
root.leftchild=createByPreOrderAndInOrder(preOrder,inOrder,begin,i-1);
/**构建右子树*/
if(i+1<=end)
root.rightchild=createByPreOrderAndInOrder(preOrder,inOrder,i+1,end);
return root;
}
private void findPathCore(BinaryTreeNode<Integer> root,int sum,
ArrayList<Integer> path,int currentSum){
currentSum+=root.value;
path.add(root.value);
/**如果是叶节点,并且路径上的值等与sum,打印出这条路径*/
boolean isLeaf=root.leftchild==null &&root.rightchild==null;
if(isLeaf && currentSum==sum){
System.out.println("sum="+sum+"的这条路径为:");
for(int i=0;i<path.size();i++){
System.out.print(path.get(i)+" ");
}
}
/**如果当前节点不是叶节点,则遍历它的子节点*/
if(root.leftchild!=null){
findPathCore(root.leftchild, sum, path, currentSum);
}
if(root.rightchild!=null){
findPathCore(root.rightchild,sum,path,currentSum);
}
currentSum-=root.value;
path.remove(path.size()-1);
}
public void findPath(BinaryTreeNode<Integer> root,int sum){
if(root==null)
return;
ArrayList<Integer> path=new ArrayList<Integer>();
int currentSum=0;
findPathCore(root,sum,path,currentSum);
}
}
public class PathInTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] preOrder={5,3,2,1,4,6,7};
Integer[] inOrder={1,2,3,4,5,6,7};
BinaryTree<Integer> tree=new BinaryTree<Integer>(preOrder[0]);
tree.root = tree.createByPreOrderAndInOrder(preOrder,inOrder,0,preOrder.length);
tree.findPath(tree.root,12);
}
}