每天一个算法之子树匹配

来源:互联网 发布:teradata数据库sql命令 编辑:程序博客网 时间:2024/05/22 00:54
package ff;


import java.util.Scanner;


class BinaryTree{
int data;
BinaryTree left;
BinaryTree right;
}
public class isSubTree {
static Scanner sc=new Scanner(System.in);
public static void main(String args[]){
BinaryTree t1=create();
BinaryTree t2=create();
System.out.println(hastree(t1,t2));
}
public static BinaryTree create(){
BinaryTree tree;
int vl=sc.nextInt();
if(vl==-1){
tree=null;
}else{
tree=new BinaryTree();
tree.data=vl;
tree.left=create();
tree.right=create();
}


return tree;

}

//如果树根的值相等,则进行判断,否则递归root1的左右子数

public static boolean hastree(BinaryTree root1,BinaryTree root2){
boolean result=false;
if(root1!=null&&root2!=null){
if(root1.data==root2.data)
result=haveTree(root1,root2);
if(!result)
result=hastree(root1.left,root2);
if(!result)
result=hastree(root1.right,root2);
}
return result;

}

//如果root2等于null说明全部对比成功,返回true,root1先为空和root1的data不等于root2的data说明匹配不成功,

private static boolean haveTree(BinaryTree root1, BinaryTree root2) {
// TODO Auto-generated method stub
if(root2==null)
return true;
if(root1==null)
return false;
if(root1.data!=root2.data)
return false;
return (haveTree(root1.left, root2.left) && haveTree(root1.right, root2.right));
}
}
0 0
原创粉丝点击