
Invert Binary Tree
I need to invert a binary tree by swapping the left and right children of every node.
From the examples, I can see that:
- Each node’s left and right children are swapped
- This happens recursively for all nodes in the tree
- The root remains the same, but its entire structure is mirrored
Time Complexity: O(n)
- Recursive: O(h) where h is the height of the tree
- Iterative: O(w) where w is themaximum width of the tree
My Code
class Solution {
func invertTree(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }
var temp = root.left
root.left = root.right
root.right = temp
invertTree(root.left)
invertTree(root.right)
return root
}
}This problem can be solved using like a BFS.