【剑指Offer】树的子结构

题目

输入两棵二叉树A和B,判断B是不是A的子结构。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
boolean result = false;

if (root1 != null && root2 != null){
if (root1.val == root2.val)
result = DoesTree1HasTree2(root1, root2);

if (result == false)
result = HasSubtree(root1.left, root2);

if (result == false)
result = HasSubtree(root1.right, root2);
}

return result;
}

private boolean DoesTree1HasTree2(TreeNode root1, TreeNode root2){
if (root2 == null)
return true;
else if (root1 == null)
return false;
else if (root1.val != root2.val)
return false;

return DoesTree1HasTree2(root1.left, root2.left) && DoesTree1HasTree2(root1.right, root2.right);
}