思路:第一步判断a的值是否和b的根结点相等不,不相等比较a的左子树和b进行比较,不同在判断a的右子树与b进行比较,重复第一步迭代。第二步,当找到a的子树和b的根结点相同时,比较该子树的左右结点 是否和b的左右结点相同。
//是否包含
public static boolean hasSubTree(TreeNote root1,TreeNote root2){
boolean result=false;
if(root1!=null&&root2!=null){
if(root1.getValue()==root2.getValue()){
result=doseTree1HasTree2(root1, root2);
}
if(!result){
result= hasSubTree(root1.getLeftTreeNote(), root2);
}
if(!result){
result=hasSubTree(root1.getRighTreeNote(), root2);
}
}
return result;
}
//是否结构一致
public static boolean doseTree1HasTree2(TreeNote root1,TreeNote root2){
if(root2==null){
return true;
}
if(root1==null){
return false;
}
if(root1.getValue()!=root2.getValue()){
return false;
}
return doseTree1HasTree2(root1.getLeftTreeNote(), root2.getLeftTreeNote())&&doseTree1HasTree2(root1.getRighTreeNote(), root2.getRighTreeNote());
}
定义二叉树
public class TreeNote {
private int value; //根节点
private TreeNote leftTreeNote; //左子树
private TreeNote rightTreeNote; //右子树
public TreeNote(){
}
public void setValue(int value){
this.value=value;
}
public int getValue(){
return value;
}
public void setLeftTreeNote(TreeNote leftTreeNote){
this.leftTreeNote=leftTreeNote;
}
public TreeNote getLeftTreeNote(){
return leftTreeNote;
}
public void setRightTreeNote(TreeNote rightTreeNote){
this.rightTreeNote=rightTreeNote;
}
public TreeNote getRighTreeNote(){
return rightTreeNote;
}
}
原文地址:http://blog.csdn.net/qq_16687803/article/details/45932545