Skip to content
BytePatterns

Mirror a Binary Tree

EasyTrees & BST#recursion#tree-traversal~10m

Problem

A layout engine stores a page as a binary tree, and right-to-left languages need the whole layout flipped. Given the root of a binary tree, swap the left and right children of every node so the tree becomes its mirror image, and return the root. The tree has up to 100 nodes. The examples show the result read level by level, left to right.

Examples

Input:  tree = 4, left 2 (children 1 and 3), right 7 (children 6 and 9)
Output: [4, 7, 2, 9, 6, 3, 1]
Why:    7 now sits on the left, and every level reads backwards
Input:  tree = 2, left 1, right 3
Output: [2, 3, 1]
Input:  tree = empty
Output: []
Why:    edge case, there is nothing to flip

Hints

0 / 3

Stuck on the idea rather than the code? Binary Trees covers it.