Skip to content

Commit ec63507

Browse files
committed
add subtree of another tree solution
1 parent 2c7c2f8 commit ec63507

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
18+
// subtree null일 경우
19+
if (subRoot == null) {
20+
return true;
21+
}
22+
// 이진 트리가 null일 경우
23+
if (root == null) {
24+
return false;
25+
}
26+
// subtree라면
27+
if (isIdentical(root, subRoot)) {
28+
return true;
29+
}
30+
31+
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
32+
33+
}
34+
35+
// isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
36+
private boolean isIdentical(TreeNode r, TreeNode s) {
37+
if (r == null || s == null) {
38+
return r == null && s == null;
39+
}
40+
if (r.val != s.val) {
41+
return false;
42+
}
43+
return isIdentical(r.left, s.left) && isIdentical(r.right, s.right);
44+
}
45+
}
46+

0 commit comments

Comments
 (0)