-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvertBinaryTree_Day_61.py
More file actions
55 lines (41 loc) · 1.33 KB
/
Copy pathInvertBinaryTree_Day_61.py
File metadata and controls
55 lines (41 loc) · 1.33 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
# Brute Approach
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# Recursive copy with swapped children
def build(node):
if not node:
return None
new_node = TreeNode(node.val)
new_node.left = build(node.right) # swap
new_node.right = build(node.left) # swap
return new_node
return build(root)
# Better: Recursive DFS
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# swap children
root.left, root.right = root.right, root.left
# recurse
self.invertTree(root.left)
self.invertTree(root.right)
return root
# Optimal: Iterative BFS
from collections import deque
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
queue = deque([root])
while queue:
node = queue.popleft()
# swap children
node.left, node.right = node.right, node.left
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root