Skip to content

Commit 2ccbfe3

Browse files
committed
update solution: invert-binary-tree
1 parent 1742c90 commit 2ccbfe3

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

invert-binary-tree/dusunax.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
- worst case: O(N), skewed tree
1616
'''
1717
class Solution:
18-
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
18+
'''
19+
DFS
20+
'''
21+
def invertTreeRecursive(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
1922
if not root:
2023
return None
2124

@@ -25,3 +28,38 @@ def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
2528
self.invertTree(root.right)
2629

2730
return root
31+
32+
'''
33+
BFS
34+
- 직관적인 stack 풀이
35+
'''
36+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
37+
stack = [root]
38+
39+
while stack:
40+
node = stack.pop()
41+
if not node:
42+
continue
43+
44+
node.left, node.right = node.right, node.left
45+
stack.append(node.left)
46+
stack.append(node.right)
47+
48+
return root
49+
50+
'''
51+
- 참고용 deque 풀이
52+
'''
53+
def invertTreeDeque(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
54+
dq = deque([root])
55+
56+
while dq:
57+
node = dq.popleft()
58+
if not node:
59+
continue
60+
61+
node.left, node.right = node.right, node.left
62+
dq.append(node.left)
63+
dq.append(node.right)
64+
65+
return root

0 commit comments

Comments
 (0)