题意:
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.
尝试
自己的思路为,通过层次遍历的方法,将每一层的元素全部保存在一个链表里,包括该位置若没有节点,则保存null,然后每层对比对称位置元素。但是超时了,原因在于思路过于复杂,开销大。代码如下,请勿参考:
import java.util.LinkedList;
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
LinkedList<TreeNode> result = new LinkedList<TreeNode>();
TreeNode p = root;
int line1 = 1, line2 = 0;
queue.offer(p);
while (!queue.isEmpty()) {
p = queue.pop();
result.offer(p);
if (p != null) {
queue.offer(p.left);
queue.offer(p.right);
} else{
queue.offer(null);
queue.offer(null);
}
line2 += 2;
if (--line1 == 0) {
while (!result.isEmpty()) {
if ((result.getFirst() == null && result.getLast() == null) || (result.getFirst().val == result.getLast().val)){
result.removeFirst();
if (!result.isEmpty()){
result.removeLast();
}
} else {
return false;
}
}
line1 = line2;
line2 = 0;
result.clear();
}
}
return true;
}
}
正确算法
参考LeetCode文档,思路为:由于要判断一棵树是不是镜像,即可以将问题转化为镜像的两棵树是不是相同,类似如图:
递归的思路
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val) && isMirror(t1.right, t2.left) && isMirror(t1.left, t2.right);
}
迭代的思路
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}