-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathmangodm-web.py
31 lines (24 loc) ยท 1.14 KB
/
mangodm-web.py
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
from typing import Optional
# Definition for a binary tree node.
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:
"""
- Idea: ๋ ํธ๋ฆฌ๋ ๊ตฌ์กฐ๊ฐ ๊ฐ๊ณ , ๊ฐ ๋
ธ๋์ ๊ฐ์ด ๊ฐ์์ผ ๊ฐ์ ํธ๋ฆฌ๋ผ๊ณ ๊ฐ์ฃผํ๋ค.
์ด๋ฅผ ํ์ธํ๊ธฐ ์ํด ์ฌ๊ท์ ์ผ๋ก ๊ฐ ๋
ธ๋๋ฅผ ๋น๊ตํ๋ค.
- Time Complexity: O(n). n์ ํธ๋ฆฌ์ ๋
ธ๋ ์.
๋ ํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ๋น๊ตํด์ผ ํ๋ฏ๋ก O(n)์ด ์์๋๋ค.
- Space Complexity: O(n). n์ ๋ฆฌ์คํธ์ ๋
ธ๋ ์.
์ฌ๊ท ํธ์ถ๋ก ์ธํด ํธ์ถ ์คํ์ ์ํ ๊ณต๊ฐ์ด ํ์ํ๋ฉฐ, ์ต์
์ ๊ฒฝ์ฐ O(n)๊น์ง ํ์ํ ์ ์๋ค.
"""
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
is_left_equal = self.isSameTree(p.left, q.left)
is_right_equal = self.isSameTree(p.right, q.right)
return is_left_equal and is_right_equal