Repository navigation
Expand file tree
/
Copy pathsolution.py
More file actions
59 lines (44 loc) · 1.61 KB
/
Copy pathsolution.py
File metadata and controls
59 lines (44 loc) · 1.61 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
from collections import deque
from leetcode_py import TreeNode
# Note: "Fringe" is the general CS term for the data structure holding nodes to be explored.
# Stack (LIFO) → DFS, Queue (FIFO) → BFS, Priority Queue → A*/Best-first search
class Solution:
# DFS recursive
# Time: O(n)
# Space: O(h) where h is height of tree
def invert_tree(self, root: TreeNode[int] | None) -> TreeNode[int] | None:
if not root:
return None
root.left, root.right = self.invert_tree(root.right), self.invert_tree(root.left)
return root
class SolutionDFS:
# DFS iterative
# Time: O(n)
# Space: O(h) where h is height of tree
def invert_tree(self, root: TreeNode[int] | None) -> TreeNode[int] | None:
if not root:
return None
stack: list[TreeNode[int] | None] = [root]
while stack:
node = stack.pop()
if node is None:
continue
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root
class SolutionBFS:
# Time: O(n)
# Space: O(w) where w is maximum width of tree
def invert_tree(self, root: TreeNode[int] | None) -> TreeNode[int] | None:
if not root:
return None
queue: deque[TreeNode[int] | None] = deque([root])
while queue:
node = queue.popleft()
if node is None:
continue
node.left, node.right = node.right, node.left
queue.append(node.left)
queue.append(node.right)
return root