Skip to content

Commit f881e4a

Browse files
committed
solve(w10): 226. Invert Binary Tree
1 parent 9a12938 commit f881e4a

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# https://leetcode.com/problems/invert-binary-tree/
2+
3+
from typing import Optional
4+
5+
# Definition for a binary tree node.
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
class Solution:
13+
def invertTree_recur1(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
14+
"""
15+
[Complexity]
16+
- TC: O(n) (๋ชจ๋“  ๋…ธ๋“œ ๋ฐฉ๋ฌธ)
17+
- SC: O(height) (call stack)
18+
19+
[Approach]
20+
DFS ์ฒ˜๋Ÿผ recursive ํ•˜๊ฒŒ ์ ‘๊ทผํ•œ๋‹ค.
21+
"""
22+
23+
def invert(node):
24+
# base condition
25+
if not node:
26+
return
27+
28+
# recur (& invert the children)
29+
node.left, node.right = invert(node.right), invert(node.left)
30+
31+
return node
32+
33+
return invert(root)
34+
35+
def invertTree_recur(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
36+
"""
37+
[Complexity]
38+
- TC: O(n)
39+
- SC: O(height) (call stack)
40+
41+
[Approach]
42+
recursive ํ•œ ๋ฐฉ๋ฒ•์—์„œ base condition ์ฒ˜๋ฆฌ ๋กœ์ง์„ ๋” ์งง์€ ์ฝ”๋“œ๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค.
43+
"""
44+
45+
def invert(node):
46+
if node:
47+
# recur (& invert the children)
48+
node.left, node.right = invert(node.right), invert(node.left)
49+
return node
50+
51+
return invert(root)
52+
53+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
54+
"""
55+
[Complexity]
56+
- TC: O(n)
57+
- SC: O(width) (queue)
58+
59+
[Approach]
60+
BFS ์ฒ˜๋Ÿผ iterative ํ•˜๊ฒŒ ์ ‘๊ทผํ•œ๋‹ค.
61+
"""
62+
from collections import deque
63+
64+
q = deque([root])
65+
66+
while q:
67+
node = q.popleft()
68+
69+
if node:
70+
# invert the children
71+
node.left, node.right = node.right, node.left
72+
73+
# add to queue
74+
q.append(node.left)
75+
q.append(node.right)
76+
77+
return root

0 commit comments

Comments
ย (0)