Skip to content

Commit 3986165

Browse files
committed
feat: solve #226 with python
1 parent 66cd1dd commit 3986165

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

invert-binary-tree/EGON.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import Optional
2+
from unittest import TestCase, main
3+
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+
13+
class Solution:
14+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
15+
return self.solve_dfs(root)
16+
17+
"""
18+
Runtime: 0 ms (Beats 100.00%)
19+
Time Complexity: O(n)
20+
> 트리의 모든 node를 방문하므로 O(n)
21+
22+
Memory: 16.53 MB (Beats 25.95%)
23+
Space Complexity: O(n)
24+
> stack의 최대 크기는 트리의 최장 경로를 이루는 node의 갯수이고, 최악의 경우 트리의 한 쪽으로 모든 node가 이어져있는 경우이므로 O(n), upper bound
25+
"""
26+
def solve_dfs(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
27+
if root is None:
28+
return root
29+
30+
stack = [root]
31+
while stack:
32+
curr_node = stack.pop()
33+
curr_node.left, curr_node.right = curr_node.right, curr_node.left
34+
if curr_node.left:
35+
stack.append(curr_node.left)
36+
if curr_node.right:
37+
stack.append(curr_node.right)
38+
39+
return root
40+
41+
42+
class _LeetCodeTestCases(TestCase):
43+
def test_1(self):
44+
return
45+
46+
47+
if __name__ == '__main__':
48+
main()

0 commit comments

Comments
 (0)