剑指Offer(书):树的子结构

题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

分析:关于二叉树大部分适应于递归结构。

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

private boolean DoesTreeHaveTree(TreeNode root1, TreeNode root2) {
    if (root2 == null) {
        return true;
    }
    if (root1 == null) {
        return false;
    }
    if (root1.val != root2.val) {
        return false;
    }
    return DoesTreeHaveTree(root1.left, root2.left) && DoesTreeHaveTree(root1.right, root2.right);
}

 

posted @ 2018-08-09 12:34  liter7  阅读(102)  评论(0编辑  收藏  举报