forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert_tree.py
More file actions
33 lines (24 loc) · 717 Bytes
/
invert_tree.py
File metadata and controls
33 lines (24 loc) · 717 Bytes
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
"""
Invert Binary Tree
Inverts a binary tree by swapping the left and right children of every node.
Reference: https://en.wikipedia.org/wiki/Binary_tree
Complexity:
Time: O(n)
Space: O(n) due to recursion stack
"""
from __future__ import annotations
from algorithms.tree.tree import TreeNode
def reverse(root: TreeNode | None) -> None:
"""Invert a binary tree in-place by swapping left and right children.
Args:
root: The root of the binary tree to invert.
Examples:
>>> reverse(None)
"""
if root is None:
return
root.left, root.right = root.right, root.left
if root.left:
reverse(root.left)
if root.right:
reverse(root.right)