判断t1树是否包含t2树全部的拓扑结构

来源:互联网 发布:淘宝店铺头像 护肤品 编辑:程序博客网 时间:2024/05/17 22:19

//判断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));   }}


阅读全文
0 0