//判断t1树是否包含t2树全部的拓扑结构
public class ContainSubTree{
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data)
{
this.value=data;
}
}
//判断是否包含
public static boolean IsContainSubTree(Node h1,Node h2)
{
if(h2==null)
{
return true;
}
if(h1==null)
{
return false;
}
//三种情况的匹配方式(递归调用)
return check(h1,h2)||IsContainSubTree(h1.left,h2)||IsContainSubTree(h1.right,h2);
}
public static boolean check(Node h1,Node h2)
{
if(h2==null)
{
return true;
}
if(h1==null||h1.value!=h2.value)
{
return false;
}
return check(h1.left,h2.left)&&check(h1.right,h2.right);
}
public static void main(String []args)
{
//System.out.print("Hello");
Node h1=new Node(1);
h1.left=new Node(2);
h1.right=new Node(3);
h1.left.left=new Node(4);
h1.left.right=new Node(5);
h1.right.left=new Node(6);
h1.right.right=new Node(7);
h1.left.left.left=new Node(8);
h1.left.left.right=new Node(9);
h1.left.right.left=new Node(10);
Node h2=new Node(2);
h2.left=new Node(4);
h2.right=new Node(5);
h2.left.left=new Node(8);
System.out.print(IsContainSubTree(h1,h2));
}
}
判断t1树是否包含t2树全部的拓扑结构
最新推荐文章于 2021-10-09 19:12:13 发布