树的子结构

题目

https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/

解法

树的遍历 注意空指针问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public boolean isSubStructure(TreeNode A, TreeNode B) {
boolean res = false;
if (A != null && B!= null) {
if (A.val == B.val) {
res = DoesTree1HaveTree2(A, B);
}
if (!res) {
res = isSubStructure(A.left, B);
}
if (!res) {
res = isSubStructure(A.right, B);
}
}
return res;
}

public boolean DoesTree1HaveTree2(TreeNode A, TreeNode B) {
if (B == null) return true;
if (A == null ) return false;
if (A.val != B.val) {
return false;
}
return DoesTree1HaveTree2(A.left, B.left) && DoesTree1HaveTree2(A.right, B.right);
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×