I was looking at interview questions and I recently came upon one that asked you how to reverse a general binary tree, like flip it from right to left.
So for example if we had the binary tree
6
/ \
3 4
/ \ / \
7 3 8 1
Reversing it would create
6
/ \
4 3
/ \ / \
1 8 3 7
You can see that the new tree is the mirror image of the original tree.
I haven’t been able to think of a good implementation on how to solve this problem. Can anyone offer any good ideas?
You can use recursion. We swap the left and right child of a node, in-place, and then do the same for its children:
To handle the case where the parameter
rootmay be null: