forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhaklee.py
More file actions
35 lines (29 loc) ยท 1.19 KB
/
haklee.py
File metadata and controls
35 lines (29 loc) ยท 1.19 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
"""TC: O(n), SC: O(h)
n์ ์ฃผ์ด์ง ํธ๋ฆฌ p, q์ ๋
ธ๋ ๊ฐ์ ์ค ๋ ์์ ์ชฝ์ ๊ฐ.
h๋ ์ฃผ์ด์ง ํธ๋ฆฌ p์ ๋์ด.
์์ด๋์ด:
- p๋ฅผ dfs๋ก ๋๋ฉด์ q๋ ๊ฐ์ ์์๋ก dfs๋ฅผ ๋๋ฆฐ๋ค.
- ์ด๋ ์ํํ๋ค๊ฐ ํ๋๋ผ๋ ๋ค๋ฅธ ๊ฐ์ด ๋์ค๋ฉด False. ๋ชจ๋ ๊ฐ์ผ๋ฉด True.
SC:
- p๋ฅผ ๊ธฐ์ค์ผ๋ก dfs๋ฅผ ๋๊ณ ์์ผ๋ฏ๋ก ํธ์ถ ์คํ์ ๊น์ด๊ฐ p์ ๊น์ด๋ณด๋ค ๊น์ด์ง ์ ์๋ค. O(h).
TC:
- ์ต์
์ ๊ฒฝ์ฐ ๋ชจ๋ ๋
ธ๋ ์ํ ํ True ๋ฆฌํด. O(n).
- False๋ฅผ ๋ฆฌํดํ ๊ฒฝ์ฐ ํธ๋ฆฌ ์ํ ์ค ๋ฉ์ถ๋ค. ์ด ๊ฒฝ์ฐ ๋ ํธ๋ฆฌ ์ค ๋ ์ ์ ๋
ธ๋ ๊ฐ์ ๋ณด๋ค
์ ์ ํ์ ๋งํผ ์ํ. ์ด ๊ฒฝ์ฐ์๋ O(n).
- ์ข
ํฉํ๋ฉด O(n).
"""
# 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:
return (p is None and q is None) or (
p is not None
and q is not None
and p.val == q.val
and self.isSameTree(p.left, q.left)
and self.isSameTree(p.right, q.right)
)