Start learning free

LESSON 477 OF 673 · BINARY TREES

Symmetric Tree

Practice O(n)

You get the root of a binary tree. Return True if the tree is symmetric. Otherwise return False.

Symmetric means the left side mirrors the right side. Flip the left subtree from left to right. It must then match the right subtree exactly, in shape and in values.

Trees are written level by level, from top to bottom and left to right. A None marks a missing child.

 

Example 1:

4 7 7 5 5
Input: root = [4,7,7,None,5,5]
Output: True
Explanation: The dashed line is the mirror.
Each 7 has its 5 on the side next to the line.
So the two sides mirror each other.

Example 2:

4 7 7 5 5
Input: root = [4,7,7,5,None,5]
Output: False
Explanation: Both red 5s are left children.
So the right side is a copy of the left, not its mirror.

Example 3:

Input: root = [9]
Output: True

 

Constraints:

  • 1 to 15 nodes.
  • Each value is a whole number from 1 to 10.
  • Values can repeat.

 

Follow up: Once a recursive version works, try one without recursion. Use a queue or a stack.
STEP 1 OF 7
    Ctrl + Enter to check