Binary Tree

Symmetric Tree Visualizer

What is Symmetric Tree

A tree is symmetric when its left side is a mirror of its right side. The outside children must match each other, and the inside children must match each other.

1 2 2 3 4 4 3
yes

Approach

Compare the root's left child with its right child. Then compare the outer pair and the inner pair, and keep going.

Outer pairThe left child of the left node mirrors the right child of the right node.
Inner pairThe right child of the left node mirrors the left child of the right node. Both must exist, or both must be missing, and the values must be equal.

The picture highlights the pair being compared. A mismatch stops the search.

Interactive solution

Mirror pairs highlighted together
def mirror(a, b):
if both are null: return True
if one is null or values differ: return False
outer = mirror(a.left, b.right)
inner = mirror(a.right, b.left)
return outer and inner
Step 0/0 Answer —

The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each node is compared once.
Call stackO(h)The mirror walk follows the height.

Implementation

def mirror(a, b):
    if not a and not b:
        return True
    if not a or not b or a.val != b.val:
        return False
    return mirror(a.left, b.right) and mirror(a.right, b.left)

def solve(self, root):
    return mirror(root.left, root.right)