题目原址
https://leetcode.com/problems/symmetric-tree/description/
题目描述
Pick One
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.
解题思路
给定一个二叉树,判断该二叉树是否是对称的,对称的含义是:同一层上的元素,第一个元素和最后一个元素相等,第二个元素和倒数第二个元素相等
这里我采用的是队列的方式按层遍历数组,非递归的方法,将数组中的每一行元素添加的队列中,如果节点没有左或者右孩子,则将其左或者右孩子的值置为Integer.MAX_VALUE,其实这个只是因为OJ没有那么多测试用例,偷个懒使用数组存储每一行数据,因为数组不能存null,所以将null存为Integer.MAX_VALUE
,这里可以使用其他的能够存储null的数据结构存储每一行数据。
AC代码
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root == null)
return true;
queue.add(root);
while(queue.size() > 0) {
int size = queue.size();
int[] arr = new int[size];
int index = 0;
for(int i = 0; i < size; i++) {
TreeNode tn = queue.poll();
if(tn == null)
arr[index ++] = Integer.MAX_VALUE;
else{
arr[index ++] = tn.val;
if(tn.left != null)
queue.add(tn.left);
else
queue.add(null);
if(tn.right != null)
queue.add(tn.right);
else
queue.add(null);
}
}
int left = 0, right = size - 1;
while(left < right) {
if(arr[left] == arr[right]){
left ++; right--;
}else
return false;
}
}
return true;
}
}