226 Invert Binary Tree
Invert a binary tree.
Complexity: O(n) time and space
DFS Approach
The idea is the same (we perform a swap on each child for each parent node. In the end, we have to be comfortable with three things. The first, is that we create N temporary Nodes, each of which have their unique local stack frame. Secondly, we move down the trees right child continuously until we hit
null
. So the first real swap will be a swap of nullptrs. However, when we return twice, the root will be2
androot->left
will have access toroot->right
, and vise-versa because of the temporary variable.
Python Solution
Last updated