Skip to content

Commit 08a6a7e

Browse files
committed
#229 Subtree of Another Tree
1 parent 8c1863a commit 08a6a7e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
# Time Complexity: O(n)
3+
# Space Complexity: O(n)
4+
- 재귀 호출 파라미터 O(n) 사이즈 공간 필요
5+
*/
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* public class TreeNode {
10+
* int val;
11+
* TreeNode left;
12+
* TreeNode right;
13+
* TreeNode() {}
14+
* TreeNode(int val) { this.val = val; }
15+
* TreeNode(int val, TreeNode left, TreeNode right) {
16+
* this.val = val;
17+
* this.left = left;
18+
* this.right = right;
19+
* }
20+
* }
21+
*/
22+
class Solution {
23+
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
24+
return dfs(root, subRoot);
25+
}
26+
27+
private boolean dfs(TreeNode root, TreeNode subRoot) {
28+
if (root == null && subRoot == null) return true;
29+
if (root == null || subRoot == null) return false;
30+
31+
if (root.val == subRoot.val) {
32+
if (compareTrees(root, subRoot)) return true;
33+
}
34+
35+
if (dfs(root.left, subRoot)) return true;
36+
if (dfs(root.right, subRoot)) return true;
37+
38+
return false;
39+
}
40+
41+
private boolean compareTrees(TreeNode root1, TreeNode root2) {
42+
if (root1 == null && root2 == null) return true;
43+
if (root1 == null || root2 == null) return false;
44+
if (root1.val != root2.val) return false;
45+
46+
return compareTrees(root1.left, root2.left) && compareTrees(root1.right, root2.right);
47+
}
48+
}

0 commit comments

Comments
 (0)