Problem
Problem page: https://leetcode.com/problems/symmetric-tree/
Topics: Tree, Depth-first Search
Difficulty: Easy
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 | 1 |
But the following is not:
1 | 1 |
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means?
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 | 1 |
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
Analysis
My first thought was to use level-order traversal on the binary tree and check whether the list of nodes at each level was symmetric from left to right. The problem suggests using recursion and backtracking. I had a hard time figuring out how to check for symmetry that way.
The recursion just compares the values of each pair of nodes in mirror positions.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-symmetric-tree/
