输入两棵二叉树A,B,判断B是不是A的子结构。
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 static void setJ(){
j=-1;
}
public BinaryTreeNode<T> createByPreOrderAndInOrder(T[] preOrder,T[] inOrder,int begin,int end){
if(preOrder==null || inOrder==null)
return null;;
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 boolean hasSubTree(BinaryTreeNode<T>root,BinaryTreeNode<T> subRoot){
if(root==null && subRoot!=null)
return false;
if( subRoot==null)
return true;
if(root.value.compareTo(subRoot.value)!=0){
return false;
}
return hasSubTree(root.leftchild,subRoot.leftchild)&&
hasSubTree(root.rightchild,subRoot.rightchild);
}
public boolean IsSubTree(BinaryTreeNode<T> root,BinaryTreeNode<T> subRoot){
boolean result=false;
if(root!=null && subRoot!=null){
if(root.value.compareTo(subRoot.value)==0){
result=hasSubTree(root,subRoot);
}
if(!result)
result=hasSubTree(root.leftchild,subRoot);
if(!result)
result=hasSubTree(root.rightchild,subRoot);
}
return result;
}
}
public class SubStructureInTree {
public static void main(String[] args) {
Integer[] preOrder1={5,3,2,1,4,6,7};
Integer[] inOrder1={1,2,3,4,5,6,7};
BinaryTree<Integer> tree=new BinaryTree<Integer>(preOrder1[0]);
tree.root = tree.createByPreOrderAndInOrder(preOrder1,inOrder1,0,preOrder1.length);
tree.inOrder(tree.root);
System.out.println();
BinaryTree1.setJ();
Integer[] preOrder={3,2,4};
Integer[] inOrder={2,1,4};
BinaryTree<Integer> treeSub=new BinaryTree<Integer>(preOrder[0]);
treeSub.root = treeSub.createByPreOrderAndInOrder(preOrder,inOrder,0,preOrder.length);
tree.inOrder(treeSub.root);
System.out.println(tree.IsSubTree(tree.root, treeSub.root));
}
}