forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_572.java
66 lines (59 loc) · 1.88 KB
/
_572.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _572 {
public static class Solution1 {
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null && t == null) {
return true;
}
boolean isSubTree = false;
if (s != null && t != null && s.val == t.val) {
isSubTree = isSameTree(s, t);
}
if (isSubTree) {
return true;
}
boolean isSubTreeLeft = false;
if (s.left != null) {
isSubTreeLeft = isSubtree(s.left, t);
}
if (isSubTreeLeft) {
return true;
}
boolean isSubTreeRight = false;
if (s.right != null) {
isSubTreeRight = isSubtree(s.right, t);
}
if (isSubTreeRight) {
return true;
}
return false;
}
private boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) {
return p == q;
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
public static class Solution2 {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) {
return false;
}
if (same(root, subRoot)) {
return true;
}
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
private boolean same(TreeNode s, TreeNode t) {
if (s == null || t == null) {
return s == t;
}
if (s.val != t.val) {
return false;
}
return same(s.left, t.left) && same(s.right, t.right);
}
}
}