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 nil marks a missing child.
Example 1:
Input: root = [4,7,7,nil,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:
Input: root = [4,7,7,5,nil,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:
1to15nodes.- Each value is a whole number from
1to10. - Values can repeat.
Follow up: Once a recursive version works, try one without recursion. Use a queue or a stack.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
