#54 · Trees · Intermediate · 55 XP · about 8 min
Write mirror(root) that turns a binary tree into its mirror image: at every node, the left and right children swap places. Change the tree in place and return its root (None for an empty tree).
Each node is a Node with a value val and two children, left and right. The provided build makes a tree from a list in level order (None marks a missing child), and the provided to_list turns a tree back into such a list, which is how the tests read your result.
5 5 / \ / \ 3 8 --> 8 3 / \ / \ / \ / \ 1 4 7 9 9 7 4 1
to_list(mirror(build([5, 3, 8, 1, 4, 7, 9]))) # returns [5, 8, 3, 9, 7, 4, 1] to_list(mirror(build([1, 2]))) # returns [1, None, 2] to_list(mirror(build([]))) # returns []
In the second example the root's only child is on the left, so after mirroring it is on the right.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.