Menu
CoddyTech

Invert Binary Tree

You get a binary tree stored in the array tree in level order. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries.

Invert the tree: swap the left and right child of every node, so the whole tree becomes its mirror image. Return the inverted tree in the same form, with no -1 entries at the end.

Function

invertTree(tree: integer-array) → integer-array
treeinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsinteger-array
the mirrored tree in level order, without trailing -1 entries

Constraints

  • 1 ≤ tree.length ≤ 16383
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 1000.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.

Examples

Input
tree = [5, 3, 8, 1, 4, -1, 9]
Output
[5, 8, 3, 9, -1, 4, 1]
Explanation
The root's children 3 and 8 trade places. Under them, the 1 and 4 below 3 come back as 4 and 1, and 8, which had only a right child 9, now has it on its left.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

How would you check whether a tree is its own mirror, using the same index pairs but without building the inverted copy?

Reset code
def invertTree(tree):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [5, 3, 8, 1, 4, -1, 9]

Expected

[5, 8, 3, 9, -1, 4, 1]