Skip to content

Commit 63c30bb

Browse files
committed
invert-binary-tree solution (py)
1 parent 1cb9892 commit 63c30bb

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

โ€Žinvert-binary-tree/hi-rachel.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
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+
์žฌ๊ท€ ํ’€์ด
12+
13+
TC: O(n), SC: O(n)
14+
n = ํŠธ๋ฆฌ ๋‚ด์˜ ๋…ธ๋“œ ์ˆ˜
15+
"""
16+
class Solution:
17+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
18+
if not root:
19+
return
20+
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
21+
return root
22+
23+
"""
24+
์Šคํƒ ํ’€์ด
25+
26+
TC: O(n), SC: O(n)
27+
"""
28+
class Solution:
29+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
30+
stack = [root]
31+
while stack:
32+
node = stack.pop()
33+
if not node:
34+
continue
35+
node.left, node.right = node.right, node.left
36+
stack += [node.left, node.right]
37+
return root

0 commit comments

Comments
ย (0)