forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseungriyou.py
More file actions
77 lines (58 loc) ยท 1.96 KB
/
seungriyou.py
File metadata and controls
77 lines (58 loc) ยท 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# https://leetcode.com/problems/invert-binary-tree/
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invertTree_recur1(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
[Complexity]
- TC: O(n) (๋ชจ๋ ๋
ธ๋ ๋ฐฉ๋ฌธ)
- SC: O(height) (call stack)
[Approach]
DFS ์ฒ๋ผ recursive ํ๊ฒ ์ ๊ทผํ๋ค.
"""
def invert(node):
# base condition
if not node:
return
# recur (& invert the children)
node.left, node.right = invert(node.right), invert(node.left)
return node
return invert(root)
def invertTree_recur(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
[Complexity]
- TC: O(n)
- SC: O(height) (call stack)
[Approach]
recursive ํ ๋ฐฉ๋ฒ์์ base condition ์ฒ๋ฆฌ ๋ก์ง์ ๋ ์งง์ ์ฝ๋๋ก ๋ํ๋ผ ์ ์๋ค.
"""
def invert(node):
if node:
# recur (& invert the children)
node.left, node.right = invert(node.right), invert(node.left)
return node
return invert(root)
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
[Complexity]
- TC: O(n)
- SC: O(width) (queue)
[Approach]
BFS ์ฒ๋ผ iterative ํ๊ฒ ์ ๊ทผํ๋ค.
"""
from collections import deque
q = deque([root])
while q:
node = q.popleft()
if node:
# invert the children
node.left, node.right = node.right, node.left
# add to queue
q.append(node.left)
q.append(node.right)
return root