Catalogue
Question
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following
[1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Analysis
要判断一个树是否对称,就是看同一层的节点是否关于中心对称。例如一层有8个节点,则应该有第一个节点值等于第八个节点值,第二个节点值等于第七个…因此在使用循环或者递归遍历树的的时候,应当使得每一步比较的两个节点位置关于中心对称。因此从每次向下遍历时,应当把每一层首位对应的两个节点送到下一步进行比较,而不是简单地把一个节点的左右子节点送到下一步。
Code
1 | class Solution(object): |