Symmetric Tree

Easy Trees

root is the root of a binary tree, which may be empty.

The tree is symmetric when it is its own mirror image: folded along a line down through the root, every node lands on a node of the same value on the other side. So the root's right subtree is its left subtree flipped from left to right, with the same values, and where a child is missing on one side, its mirror image is missing too.

Return true when the tree is symmetric and false when it is not. The empty tree, and a tree of one node, are symmetric.

Example 1

Input: root = [6,3,3,8,null,null,8,2,5,5,2]
Output: true
633882552

Fold the tree along a line down through 6. The two 3s meet. The 8 on the far left, under the left 3, meets the 8 on the far right, under the right 3. Below them, 2 meets 2 and 5 meets 5, each on the other side.

Example 2

Input: root = [7,1,1,9,null,9]
Output: false
71199

Example 3

Input: root = [9,4,4,1,7,1,7]
Output: false
9441717

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -10⁴ ≤ node.val ≤ 10⁴

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Trees

All Trees problems