Skip to content

Commit 0102691

Browse files
committed
feat: Upload same-tree (typescript)
1 parent d751f6a commit 0102691

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

same-tree/mike2ox.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Source: https://leetcode.com/problems/same-tree/
3+
* Solution: 트리의 노드를 순회하면서 값이 같은지 확인
4+
* 시간 복잡도: O(N) - 트리의 모든 노드를 한번씩 방문
5+
* 공간 복잡도: O(N) - 스택에 최대 트리의 높이만큼 쌓일 수 있음
6+
*
7+
* 추가 사항
8+
* - 트리를 순회만 하면 되기에 Typescript로 Stack을 활용해 DFS로 해결
9+
* - 재귀로 구현하면 간단하게 구현 가능
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* class TreeNode {
15+
* val: number
16+
* left: TreeNode | null
17+
* right: TreeNode | null
18+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
19+
* this.val = (val===undefined ? 0 : val)
20+
* this.left = (left===undefined ? null : left)
21+
* this.right = (right===undefined ? null : right)
22+
* }
23+
* }
24+
*/
25+
26+
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
27+
if (!q || !p) return !q === !p;
28+
let result = true;
29+
let stack = new Array({
30+
left: p,
31+
right: q,
32+
});
33+
while (stack.length) {
34+
const now = stack.pop();
35+
const left = now?.left;
36+
const right = now?.right;
37+
const isLeafNode =
38+
!left?.left && !left?.right && !right?.right && !right?.left;
39+
const isSameValue = left?.val === right?.val;
40+
const hasDifferentSubtree =
41+
(!left?.left && right?.left) || (!left?.right && right?.right);
42+
if (isLeafNode && isSameValue) continue;
43+
if (!isSameValue || hasDifferentSubtree) {
44+
result = false;
45+
break;
46+
}
47+
stack.push({ left: left?.left, right: right?.left });
48+
stack.push({ left: left?.right, right: right?.right });
49+
}
50+
return result;
51+
}
52+
53+
// Solution 2 - 재귀
54+
function isSameTree2(p: TreeNode | null, q: TreeNode | null): boolean {
55+
if (!p && !q) return true;
56+
if (!p || !q) return false;
57+
if (p.val !== q.val) return false;
58+
59+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
60+
}

0 commit comments

Comments
 (0)