Workspace

Problem workspace

3 day streakD

Symmetric Tree

EasyTreesTree properties

The challenge

Check whether the tree is a mirror of itself in both values and shape.

Null positions matter. An empty tree is symmetric.

Example

The first example is symmetric; the sparse example has equal values but mismatched child positions.

Use the walkthrough below to inspect the input and each state change.

See Symmetry, step by step

Follow the branches. Watch the state change.

7 input nodesL = left · R = right
Inspect the input.Labels identify node objects; numbers are their values. Left and right child pointers define the tree. Node labels identify objects; numbers show their values. The pointer table below provides the same structure in text.LRLRLR3D2B4E1A · root4F2C3G
CurrentProcessedPending
View child pointers & node state
Node state · null means no child
NodeValueLeftRightState
A1BC—
B2DE—
C2FG—
D3nullnull—
E4nullnull—
F4nullnull—
G3nullnull—
Step 01 / 9

Inspect the input.

Labels identify node objects; numbers are their values. Left and right child pointers define the tree.

root = A:1
View original input

A:1 [L:B, R:C] · B:2 [L:D, R:E] · C:2 [L:F, R:G] · D:3 [L:null, R:null] · E:4 [L:null, R:null] · F:4 [L:null, R:null] · G:3 [L:null, R:null]

Node IDs stay distinct even when values repeat. Pointer mutations update the diagram; removed nodes remain in the state table for reference.

Put it into code

Compare pairs of positions reflected across the root.

Nodes store value, left, and right. C++ uses C++17 or later.

from collections import deque

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def is_symmetric(root):
    def mirror(a, b):
        if a is None or b is None:
            return a is b
        return (a.value == b.value
                and mirror(a.left, b.right)
                and mirror(a.right, b.left))
    return root is None or mirror(root.left, root.right)

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap