Skip to content

Commit 1e14edd

Browse files
Jeehay28Jeehay28
authored andcommitted
Add subtree-of-another-tree solution in TS
1 parent 6529ad5 commit 1e14edd

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

subtree-of-another-tree/Jeehay28.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
// TC: O(m + n), m = number of nodes in root, n = number of nodes in subRoot
13+
// SC: O(m + n)
14+
function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
15+
const serializeNode = (node: TreeNode | null) => {
16+
if (!node) return "$";
17+
18+
const str = `(${node.val},${serializeNode(node.left)},${serializeNode(
19+
node.right
20+
)})`;
21+
22+
return str;
23+
};
24+
25+
const serializedRoot = serializeNode(root);
26+
const serializedSubRoot = serializeNode(subRoot);
27+
28+
return serializedRoot.includes(serializedSubRoot);
29+
}

0 commit comments

Comments
 (0)