Skip to content

Commit 41a8374

Browse files
committed
add Same Tree solution
1 parent bfe0319 commit 41a8374

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

same-tree/HoonDongKang.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* [Problem]: [100] Same Tree
3+
* (https://leetcode.com/problems/same-tree/description/)
4+
*/
5+
6+
class TreeNode {
7+
val: number;
8+
left: TreeNode | null;
9+
right: TreeNode | null;
10+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
11+
this.val = val === undefined ? 0 : val;
12+
this.left = left === undefined ? null : left;
13+
this.right = right === undefined ? null : right;
14+
}
15+
}
16+
17+
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
18+
// 시간복잡도 O(N)
19+
// 공간복잡도 O(N)
20+
function recursiveFunc(p: TreeNode | null, q: TreeNode | null): boolean {
21+
if (!p && !q) return true;
22+
if (!p || !q) return false;
23+
if (p.val !== q.val) return false;
24+
return recursiveFunc(p.left, q.left) && recursiveFunc(p.right, q.right);
25+
}
26+
27+
// 시간복잡도 O(N)
28+
// 공간복잡도 O(N)
29+
function stackFunc(p: TreeNode | null, q: TreeNode | null): boolean {
30+
const stack = [[p, q]];
31+
while (stack.length) {
32+
const [p, q] = stack.pop()!;
33+
if (!p && !q) continue;
34+
if (!p || !q) return false;
35+
if (p.val !== q.val) return false;
36+
37+
stack.push([p.left, q.left]);
38+
stack.push([p.right, q.right]);
39+
}
40+
41+
return true;
42+
}
43+
}

0 commit comments

Comments
 (0)