Menu
CoddyTech

Symmetric 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. Return true if the tree is a mirror image of itself around a vertical line through the root, and false otherwise. The shape and the values must both match.

Function

isSymmetric(tree: integer-array) → boolean
treeinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsboolean
true if the tree mirrors itself, false otherwise

Constraints

  • 1 ≤ tree.length ≤ 32767
  • 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 = [1, 2, 2, 3, 4, 4, 3]
Output
true
Explanation
Fold the tree down the middle. The two 2s at indexes 1 and 2 meet, the outer 3s at indexes 3 and 6 meet, and the inner 4s at 4 and 5 meet.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

If the shape mirrors itself but some values do not, what is the fewest node values you must change to make the tree symmetric?

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

Case 1

Case 2

Case 3

Input

tree = [1, 2, 2, 3, 4, 4, 3]

Expected

true