oneby7

Binary Trees Depth first: return a value up

356. Symmetric Tree

Easy

You are given root, the root node of a binary tree. Return true if the tree is symmetric, and false otherwise.

A tree is symmetric when it is the mirror image of itself. Draw a vertical line through the root and fold the tree along it. The tree is symmetric when every node lands on a node with the same value, and no node lands on an empty place.

Leave the tree as you found it. When your function returns, every node must still have its own value and its own two children.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

-25794975-2

Input: root = [4, 7, 7, -2, 9, 9, -2, null, 5, null, null, null, null, 5]

Output: true

Explanation: Folded along the line through 4, the two 7s meet, the outer −2s meet and the inner 9s meet. The 5 under the left −2 is its right child, and the 5 under the right −2 is its left child, so they meet too.

Example 2

16316

Input: root = [3, 1, 1, null, 6, null, 6]

Output: false

Explanation: Both 1s have a right child 6. For a mirror image, the right 1 would need its 6 on the left.

Example 3

-8

Input: root = [-8]

Output: true

Explanation: A single node has nothing beside it, so it is its own mirror image.

Check your understanding

Work out the answer for this input before you write any code.

root = [2, 3, 3, 4, 5, 4, 5]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.