Skip to content

Commit 45d187d

Browse files
committed
solve: subtree of another tree
1 parent 087e190 commit 45d187d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

subtree-of-another-tree/wogha95.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* tree를 순회하면서 subRoot의 시작값과 동일한 노드를 찾습니다.
3+
* 찾으면 동일한 트리인지 확인합니다.
4+
*
5+
* TC: O(N)
6+
* 최악의 경우, root tree의 모든 node를 순회합니다.
7+
*
8+
* SC: O(N)
9+
* 최악의 경우, root tree의 모든 node를 순회하기 위해 queue를 사용합니다.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @param {TreeNode} subRoot
23+
* @return {boolean}
24+
*/
25+
var isSubtree = function (root, subRoot) {
26+
const queue = [root];
27+
28+
while (queue.length > 0) {
29+
const current = queue.shift();
30+
31+
if (!current) {
32+
continue;
33+
}
34+
35+
if (current.val === subRoot.val && isSameTree(current, subRoot)) {
36+
return true;
37+
}
38+
39+
if (current.left) {
40+
queue.push(current.left);
41+
}
42+
43+
if (current.right) {
44+
queue.push(current.right);
45+
}
46+
}
47+
48+
return false;
49+
50+
function isSameTree(rootA, rootB) {
51+
if (rootA === null && rootB === null) {
52+
return true;
53+
}
54+
55+
if (rootA === null || rootB === null) {
56+
return false;
57+
}
58+
59+
return (
60+
rootA.val === rootB.val &&
61+
isSameTree(rootA.left, rootB.left) &&
62+
isSameTree(rootA.right, rootB.right)
63+
);
64+
}
65+
};

0 commit comments

Comments
 (0)