剑指offer:面试题18、树的子结构
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
代码示例
public class Offer18 {
public static void main(String[] args) {
//构建树1
TreeNode root1 = new TreeNode(1);
root1.left = new TreeNode(2);
root1.right = new TreeNode(3);
root1.left.left = new TreeNode(4);
root1.left.right = new TreeNode(5);
//构建树2
TreeNode root2 = new TreeNode(1);
root2.left = new TreeNode(2);
root2.right = new TreeNode(3);
//for test
Offer18 testObj = new Offer18();
System.out.println(testObj.hasSubTree(root1, root2));
}
static class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
TreeNode(int val) {
this.val = val;
}
}
public boolean hasSubTree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
return isSubtreeFromRoot(root1,root2) || hasSubTree(root1.left, root2) || hasSubTree(root1.right, root2);
}
//从根节点依次向下比较
private boolean isSubtreeFromRoot(TreeNode root1, TreeNode root2) {
if (root2 == null)
return true;//已经递归到root2没有节点了
if (root1 == null)
return false;//root2不为null而root1为null所以返回false
if (root1.val != root2.val)
return false;
//递归判定左右节点是否都满足要求
return isSubtreeFromRoot(root1.left, root2.left)
&& isSubtreeFromRoot(root1.right, root2.right);
}
}