判断树的子结构——剑指offer

思路很简单:先找到匹配的根节点,再在树1的左子树和右子树里面进行遍历
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result = false;
        if(root1!=null && root2!=null){
           if(root1.val==root2.val){
               result = DoesTreeHasNextTree(root1,root2);
           }
           if(!result){
               result = HasSubtree(root1.left,root2);
           }
           if(!result){
               result =  HasSubtree(root1.right,root2);
           }
        }
        return result;
    }
    public static boolean DoesTreeHasNextTree(TreeNode t1,TreeNode t2){
        if(t2==null){
            return true;
        }
        if(t1==null){
            return false;
        }
        if(t1.val!=t2.val){
            return false;
        }
        return DoesTreeHasNextTree(t1.left,t2.left)&&DoesTreeHasNextTree(t1.right,t2.right);
    }
}
View Code

 

posted @ 2017-05-14 01:30  dortmund  阅读(208)  评论(0编辑  收藏  举报