题目链接
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
解题思路
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if (root1==null || root2==null) return false;
return isSubTreeWithRoot(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
}
private boolean isSubTreeWithRoot(TreeNode node1, TreeNode node2) {
if (node2==null) return true;
if (node1==null) return false;
if (node1.val != node2.val) return false;
return isSubTreeWithRoot(node1.left, node2.left) && isSubTreeWithRoot(node1.right, node2.right);
}
}