二叉树的包含情况

来源:互联网 发布:java se8 程序设计 编辑:程序博客网 时间:2024/04/28 16:20

判断一个二叉树是否包含另一个二叉树

package tree;/** * Created by Administrator on 2015/10/8 0008. */public class TreeContain {    public static void main(String[] args) {        int a[]={5,3,7,9,2,8};        int b[]={3};        BinaryTree root1=new BinaryTree(a[0]);        BinaryTree root2=new BinaryTree(b[0]);        for(int i=1;i<a.length;i++){            root1.insert(root1,a[i]);        }        for(int i=1;i<b.length;i++){            root2.insert(root2,b[i]);        }        /*root1.preTraval(root1);        root2.preTraval(root2);*/        System.out.println(panduan(root1, root2));    }    public static boolean panduan(BinaryTree root1, BinaryTree root2){        boolean flag=false;        if(root1!=null&&root2!=null){            if(root1.value==root2.value)                flag=deepPanduan(root1,root2);            if(!flag)                flag=panduan(root1.lchild,root2);            if(!flag)                flag=panduan(root1.rchild,root2);        }        return flag;    }    private static boolean deepPanduan(BinaryTree root1, BinaryTree root2) {        if(root1==null)            return false;        else if(root2==null)            return true;        if(root1.value!=root2.value)            return false;        return deepPanduan(root1.lchild,root2.lchild)&&deepPanduan(root1.rchild,root2.rchild);       /* if(root2.lchild==null&&root2.rchild!=null)            return deepPanduan(root1.rchild,root2.rchild);        if(root2.lchild!=null&&root2.rchild==null)            return deepPanduan(root1.lchild,root2.lchild);        return false;*/    }}

不知道是不是因为主函数树的构造关系,测试时,是根节点就会成功,如果有其他节点就会false

我知道了,就是在deepPanduan函数中,理应判断root2是否为空或者root1是否为空在进行返回值的确定,而上面所写的没有直接关系

 if(root1==null)            return false;        else if(root2==null)            return true;
是不对的,理应是并列的

if(root2==null)            return true;        if(root1==null)            return false;
所以最终deepPanduan函数为:

private static boolean deepPanduan(BinaryTree root1, BinaryTree root2) {        if(root2==null)            return true;        if(root1==null)            return false;        if(root1.value!=root2.value)            return false;        return deepPanduan(root1.lchild,root2.lchild)&&deepPanduan(root1.rchild,root2.rchild);    }

哈哈,这样就可以了

0 0
原创粉丝点击