The problem “Invert Binary Tree” asks you to invert a given binary tree. An inverted (or mirrored) binary tree is one where the left and right children of all nodes are swapped.
Given the root of a binary tree, invert the tree, and return its root.
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
val
, left
, and right
.[0, 100]
.[-100, 100]
.None
)?
None
, we should return None
.To solve this problem, we can use a recursive approach:
None
, return None
because there’s nothing to invert.An iterative approach using a queue (BFS) or stack (DFS) can also accomplish this task, but the recursive method is straightforward and easy to implement for binary tree problems.
# 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
def invertTree(root: TreeNode) -> TreeNode:
# Base case: if the root is None, return None
if root is None:
return None
# Swap the left and right children
root.left, root.right = root.right, root.left
# Recursively invert both subtrees
invertTree(root.left)
invertTree(root.right)
return root
The time complexity of this approach is (O(n)), where (n) is the number of nodes in the tree. This is because in the worst-case scenario, we need to visit every node once to invert the tree.
The space complexity is (O(h)), where (h) is the height of the tree, due to the recursion stack. In the worst case, (h) could be (O(n)) for a skewed tree, making the worst-case space complexity (O(n)). For a balanced tree, the space complexity is (O(\log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?