树的子结构

题目:输入两个二叉树A和B,判断B是不是A的子结构。

public boolean HasSubtree(Node Tree1,Node Tree2){
        boolean result = false;
        if(Tree1 != null && Tree2 != null){
            if(Tree1.data == Tree2.data){
                result = DoesTree1HaveTree2(Tree1,Tree2);
            }
            if(!result){
                result = HasSubtree(Tree1.left,Tree2);
            }
            if(!result){
                result = HasSubtree(Tree1.right,Tree2);
            }
        }
    }
    
    public boolean DoesTree1HaveTree2(Node Tree1,Node Tree2){
        if(Tree1 == null){
            return false;
        }
        if(Tree2 == null){
            return true;
        }
        if(Tree1.data != Tree2.data){
            return false;
        }
        return DoesTree1HaveTree2(Tree1.left,Tree2,left) && DoesTree1HaveTree2(Tree1.right,Tree2.right);
    }

 

posted @ 2018-07-09 00:43  樱圃  阅读(117)  评论(0编辑  收藏  举报