面试题:树的子结构

题目描述

思路:先在A树中先找到和B树根节点一样的值 然后判断二者结构是否相同

public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result=false;
        if(root1!=null&&root2!=null){
            if(root1.val==root2.val)
                result=doesTree1Tree2(root1,root2);
            if(!result) {result=HasSubtree(root1.left,root2);}
            if(!result) {result=HasSubtree(root1.right,root2);}
        }
        return result;
    }
    public boolean doesTree1Tree2(TreeNode root1,TreeNode root2) {
        if(root1==null&&root2!=null) return false;
        if(root2==null) return true;
        if(root1.val!=root2.val) return false;
        return doesTree1Tree2(root1.left,root2.left)&&doesTree1Tree2(root1.right,root2.right);
    }
}

 

posted on 2018-08-25 10:34  Aaron12  阅读(126)  评论(0编辑  收藏  举报

导航