-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathmike2ox.ts
60 lines (56 loc) ยท 1.9 KB
/
mike2ox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Source: https://leetcode.com/problems/same-tree/
* Solution: ํธ๋ฆฌ์ ๋
ธ๋๋ฅผ ์ํํ๋ฉด์ ๊ฐ์ด ๊ฐ์์ง ํ์ธ
* ์๊ฐ ๋ณต์ก๋: O(N) - ํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ํ๋ฒ์ฉ ๋ฐฉ๋ฌธ
* ๊ณต๊ฐ ๋ณต์ก๋: O(N) - ์คํ์ ์ต๋ ํธ๋ฆฌ์ ๋์ด๋งํผ ์์ผ ์ ์์
*
* ์ถ๊ฐ ์ฌํญ
* - ํธ๋ฆฌ๋ฅผ ์ํ๋ง ํ๋ฉด ๋๊ธฐ์ Typescript๋ก Stack์ ํ์ฉํด DFS๋ก ํด๊ฒฐ
* - ์ฌ๊ท๋ก ๊ตฌํํ๋ฉด ๊ฐ๋จํ๊ฒ ๊ตฌํ ๊ฐ๋ฅ
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (!q || !p) return !q === !p;
let result = true;
let stack = new Array({
left: p,
right: q,
});
while (stack.length) {
const now = stack.pop();
const left = now?.left;
const right = now?.right;
const isLeafNode =
!left?.left && !left?.right && !right?.right && !right?.left;
const isSameValue = left?.val === right?.val;
const hasDifferentSubtree =
(!left?.left && right?.left) || (!left?.right && right?.right);
if (isLeafNode && isSameValue) continue;
if (!isSameValue || hasDifferentSubtree) {
result = false;
break;
}
stack.push({ left: left?.left, right: right?.left });
stack.push({ left: left?.right, right: right?.right });
}
return result;
}
// Solution 2 - ์ฌ๊ท
function isSameTree2(p: TreeNode | null, q: TreeNode | null): boolean {
if (!p && !q) return true;
if (!p || !q) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}