每天一个算法之子树匹配
来源:互联网 发布: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;
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;
// 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));
}
}
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
- 每天一个算法之子树匹配
- 每天一个算法之树镜像
- 每天一个排序算法之插入排序
- 每天一个算法之移位运算
- 每天一个算法之指数运算
- 每天一个算法之奇偶异侧
- 每天一个算法之链表逆序
- 每天一个算法之顺时针打印矩阵
- 每天一个算法之字符串子序列
- 每天一个小算法之 选择排序算法
- 每天一个算法
- 每天一个算法练习之字符空格替换
- 每天一个算法之根据前序中序序列重建二叉树
- 每天一个算法之二维数组查找整数
- 每天一个算法之两栈实现队列
- 每天一个算法之fibonacci递归法优化
- 每天一个算法之链表中倒数第K个结点
- 每天一个算法之合并有序链表
- 组合模式(Composite Pattern)
- C++虚函数实现机制
- Golden Goose Homme from The Xian Xian
- 字符的几种编码方式
- Git from the inside out
- 每天一个算法之子树匹配
- houdini批渲染结束自动关机程序
- RMI
- java自带的MessageDigest实现文本的md5加密算法
- MySQL基础教程
- Git 基础 - 撤消操作
- delete 和 delete []
- 八皇后问题
- Number of Islands