Binary Trees Depth first: return a value up
356. Symmetric Tree
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
Input: root = [4, 7, 7, -2, 9, 9, -2, null, 5, null, null, null, null, 5]
trueExplanation: 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
Input: root = [3, 1, 1, null, 6, null, 6]
falseExplanation: Both 1s have a right child 6. For a mirror image, the right 1 would need its 6 on the left.
Example 3
Input: root = [-8]
trueExplanation: 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.
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.