Skip to content

Commit 86cd574

Browse files
authored
[ PS ] : Subtree of Another Tree
1 parent 5fddc45 commit 86cd574

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {TreeNode} subRoot
12+
* @return {boolean}
13+
*/
14+
const isSubtree = function(root, subRoot) {
15+
const isSame = function(node1, node2) {
16+
if (!node1 && !node2) return true;
17+
if (node1?.val !== node2?.val) return false;
18+
19+
return isSame(node1.left, node2.left) && isSame(node1.right, node2.right);
20+
}
21+
22+
const queue = [root];
23+
24+
while (queue.length) {
25+
const node = queue.shift();
26+
27+
if (node.left) {
28+
queue.push(node.left);
29+
}
30+
31+
if (node.right) {
32+
queue.push(node.right);
33+
}
34+
35+
if (isSame(node, subRoot)) {
36+
return true;
37+
}
38+
}
39+
40+
return false;
41+
};
42+
43+
// ๋‹ค๋ฅธ ์ ‘๊ทผ๋ฒ•:
44+
// ์ •๋ ฌํ•ด์„œ ๋น„๊ตํ•˜๋Š” ๋ฐฉ์‹ => left, right ๊ตฌ๋ถ„์ด ์•ˆ๊ฐ€๋Š” ๋ฌธ์ œ
45+
// ์ •๋ ฌํ•  ๋•Œ left, right ์ •๋ณด๋ฅผ ํฌํ•จํ•ด์„œ ์ง๋ ฌํ™”ํ•˜๋ฉด ๋จ
46+
// ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋ณต์žก๋„ ๋ฉด์—์„œ ์„ฑ๋Šฅ์ด ๋” ์ข‹์Œ
47+
48+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n * m) (n: root size, m: subroot size)
49+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(n + m)

0 commit comments

Comments
ย (0)