forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocow.py
More file actions
58 lines (45 loc) ยท 1.32 KB
/
socow.py
File metadata and controls
58 lines (45 loc) ยท 1.32 KB
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
"""
100. Same Tree
๋ฌธ์ ์์ฝ
- ๋ ์ด์ง ํธ๋ฆฌ๊ฐ ๋๊ฐ์์ง ํ์ธํ๊ธฐ
- ๊ตฌ์กฐ๋ ๊ฐ๊ณ , ๊ฐ๋ ๊ฐ์์ผ True
๋ฌธ์ ์์
ํธ๋ฆฌ1: ํธ๋ฆฌ2:
1 1
/ \ / \
2 3 2 3
โ True (์์ ๋์ผ!)
ํธ๋ฆฌ1: ํธ๋ฆฌ2:
1 1
/ \
2 2
โ False (๊ตฌ์กฐ๊ฐ ๋ค๋ฆ!)
ํต์ฌ ์๊ณ ๋ฆฌ์ฆ
- ํจํด: ์ฌ๊ท (DFS)
- ์๊ฐ๋ณต์ก๋: O(n) - ๋ชจ๋ ๋
ธ๋ ๋ฐฉ๋ฌธ
- ๊ณต๊ฐ๋ณต์ก๋: O(h) - h๋ ํธ๋ฆฌ ๋์ด
ํต์ฌ ์์ด๋์ด
1. ๋ ๋ค None โ True
2. ํ๋๋ง None โ False
3. ๊ฐ์ด ๋ค๋ฆ โ False
4. ์ผ์ชฝ ์๋ธํธ๋ฆฌ ๋น๊ต & ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ๋น๊ต
"""
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# ๋ ๋ค None โ ๊ฐ์!
if not p and not q:
return True
# ํ๋๋ง None โ ๋ค๋ฆ!
if not p or not q:
return False
# ๊ฐ์ด ๋ค๋ฆ โ ๋ค๋ฆ!
if p.val != q.val:
return False
# ์ผ์ชฝ๋ผ๋ฆฌ ๋น๊ต AND ์ค๋ฅธ์ชฝ๋ผ๋ฆฌ ๋น๊ต
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)