-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubtreeOfAnotherTree.java
49 lines (43 loc) · 1.14 KB
/
SubtreeOfAnotherTree.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
package binarytree;
import binarytree.BinaryTreeTest.TreeNode;
/**
* @author Shogo Akiyama
* Solved on 08/29/2019
*
* 572. Subtree of Another Tree
* https://leetcode.com/problems/subtree-of-another-tree/
* Difficulty: Easy
*
* Approach: Recursion
* Runtime: 1 ms, faster than 100.00% of Java online submissions for Subtree of Another Tree.
* Memory Usage: 40.6 MB, less than 95.56% of Java online submissions for Subtree of Another Tree.
*
* @see BinaryTreeTest#testSubtreeOfAnotherTree()
*/
public class SubtreeOfAnotherTree {
public boolean isSubtree(TreeNode s, TreeNode t) {
if (t == null && s == null) {
return true;
} else if (s == null) {
return false;
} else if (s != null && t == null) {
return false;
}
if (s.val == t.val) {
boolean b = true;
if (s.left != null && t.left != null) {
b = (s.left.val == t.left.val);
}
if (s.right != null && t.right != null) {
b = (s.right.val == t.right.val);
}
if (b == true) {
b = isSubtree(s.left, t.left) && isSubtree(s.right, t.right);
}
if (b == true) {
return true;
}
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
}