root = [4,2,7,1,3,6,9][4,7,2,9,6,3,1]Mirror a binary tree by exchanging the left and right children at every node. Return the root of the changed tree. Values stay attached to their nodes.
root = [4,2,7,1,3,6,9][4,7,2,9,6,3,1]Lists show level order. null means a missing child. Swapping only the root's children is not enough: each subtree must also be mirrored.
root = [][]An empty tree stays empty.
root = [4,2,7,1,3,6,9] output: [4,7,2,9,6,3,1]
Every node is visited once and its two child references are exchanged in constant time.
The active recursive calls use O(h) space, where h is the tree height. This is O(log n) for a balanced tree and O(n) for a skewed tree.
root = [4,2,7,1,3,6,9] output: [4,7,2,9,6,3,1]
Both approaches take O(n) time and change the tree in place. Iteration avoids Python's recursion limit; it does not guarantee constant extra space.
Every node is visited once and its two child references are exchanged in constant time.
The pending-node stack is bounded by O(h), at most O(n). A single chain keeps only one pending node in this implementation.