Skip to content

Commit e2c140b

Browse files
committed
feat: add invert binary tree solution
1 parent a3c9195 commit e2c140b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

โ€Žinvert-binary-tree/mangodm-web.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import Optional
2+
3+
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
11+
class Solution:
12+
"""
13+
- Idea: ์žฌ๊ท€๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ ๋…ธ๋“œ์˜ ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹์„ ๋ฐ”๊พผ๋‹ค.
14+
- Time Complexity: O(n). n์€ ์ „์ฒด ๋…ธ๋“œ์˜ ์ˆ˜๋‹ค.
15+
๋ชจ๋“  ๋…ธ๋“œ์— ๋Œ€ํ•ด์„œ ๋ฐ˜๋ณต์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— O(n) ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฐ๋‹ค.
16+
- Space Complexity: O(h). h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด๋กœ, ์žฌ๊ท€ ํ˜ธ์ถœ์œผ๋กœ ์ธํ•œ ์Šคํƒ ๊ณต๊ฐ„์ด ํ•„์š”ํ•˜๋‹ค.
17+
"""
18+
19+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
20+
if root is None:
21+
return
22+
23+
root.left, root.right = root.right, root.left
24+
25+
self.invertTree(root.left)
26+
self.invertTree(root.right)
27+
28+
return root

0 commit comments

Comments
ย (0)