forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKwonNayeon.py
More file actions
33 lines (28 loc) ยท 1.05 KB
/
KwonNayeon.py
File metadata and controls
33 lines (28 loc) ยท 1.05 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
"""
Constraints:
- The number of nodes in both trees is in the range [0, 100].
- -10^4 <= Node.val <= 10^4
Time Complexity: O(n)
- ๊ฐ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ
Space Complexity: O(h)
- ์ฌ๊ท ํธ์ถ ์คํ์ ๊น์ด๋ ํธ๋ฆฌ์ ๋์ด(h)์ ๋น๋กํจ
ํ์ด๋ฐฉ๋ฒ:
1. DFS์ ์ฌ๊ท๋ฅผ ํ์ฉํ์ฌ ๋ ํธ๋ฆฌ๋ฅผ ๋์์ ํ์
2. base case:
- p์ q๊ฐ ๋ชจ๋ None์ผ ๋: ๊ฐ์ ํธ๋ฆฌ
- ๋ ์ค ํ๋๋ง None์ด๊ฑฐ๋ ๋
ธ๋์ ๊ฐ์ด ๋ค๋ฅผ ๋: ๋ค๋ฅธ ํธ๋ฆฌ
3. ์ฌ๊ท๋ก ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๊ฐ ๋ชจ๋ ๊ฐ์์ง ํ์ธ
"""
# 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:
if p is None and q is None:
return True
if p is None or q is None or p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)