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
32 lines (25 loc) ยท 974 Bytes
/
haklee.py
File metadata and controls
32 lines (25 loc) ยท 974 Bytes
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
"""TC: O(n), SC: O(h)
h๋ ์ด์ง ํธ๋ฆฌ์ ๋์ด.
n์ด ์ ์ฒด ๋
ธ๋ ๊ฐ์๋ผ๊ณ ํ ๋
- ์ต์
์ ๊ฒฝ์ฐ ํ ์ชฝ ์์ ๋
ธ๋๋ง ์ฑ์์ง. ์ด ๊ฒฝ์ฐ h = n.
- ์ต์ ์ ๊ฒฝ์ฐ ์์ ์ด์ง ํธ๋ฆฌ. h = log(n).
์์ด๋์ด:
์์ชฝ ์์ ๋
ธ๋์ ์ ๊ทผํด์ ์ฌ๊ท์ ์ผ๋ก invert๋ฅผ ์งํํ๊ณ , ๋ ์์ ๋
ธ๋๋ฅผ ๋ฐ๊พผ๋ค.
SC:
- ํธ์ถ ์คํ ๊น์ด๋ ํธ๋ฆฌ์ ๊น์ด๊น์ง ๊น์ด์ง ์ ์๋ค. ์ฆ, O(h).
TC:
- ๋ชจ๋ ๋
ธ๋์ ์ ๊ทผ. 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def invert(node: Optional[TreeNode]) -> None:
if node is not None:
node.left, node.right = invert(node.right), invert(node.left)
return node
return invert(root)