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.
解法1:Recursive
主要还是分治的思想,对称的意思就是left = right,实际上我们要比较的是left tree 和right tree。
需要满足的条件是left.left = right.right && left.right = right.left
然后不停的递归下去就可以了。
C++
|
|
解法2:Iteratively
非递归一般需要用额外的数据结构,这里可以想到的是用queue,然后做一个BFS(按层遍历)。和比较是否是same tree很像,唯一不一样的是这里left需要从左往右,而right需要从右往左。
参考了喜唰唰的解法。
C++
|
|