Swap children of selected binary tree nodes in place
An org-chart viewer draws each manager’s two reports as a left and a right box. For right-to-left languages it mirrors the whole chart, and for some layouts it only mirrors certain levels or certain teams. All of these come down to one operation: walk the tree and swap the children of the nodes you are told to swap.
Implement flipTree(root, shouldFlip). It swaps the left and right children of every node selected by shouldFlip, in place, and returns root.
flipTree(root, shouldFlip?) // => root
// shouldFlip(node, depth) => truthy to swap this node's children
{ value, left, right }. left and right are nodes or null.root is a node or null.shouldFlip is optional. When it is missing, every node is flipped, which mirrors the whole tree.shouldFlip(node, depth) exactly once for every node in the tree. The root has depth 0, its children depth 1, and so on. A node is always checked before any of its descendants.left and right. A leaf swaps two nulls, which changes nothing.left and right. Return the same root, or null for an empty tree.// 1 1
// / \ / \
// 2 3 => 3 2
// / \ \ / / \
// 4 5 6 6 5 4
flipTree(root); // mirrors every level
// 1 1
// / \ / \
// 2 3 => 2 3
// / \ / \ / \ / \
// 4 5 6 7 5 4 7 6
flipTree(root, (node, depth) => depth === 1); // only the second level
flipTree(root, (node) => node.value % 2 === 0); // only nodes with even values
flipTree(null); // => null