题目
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
题解:
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return symmetric(root.left, root.right);
}
private boolean symmetric(TreeNode p, TreeNode q){
if(p== null && q == null){
return true;
}
if( p == null || q== null){
return false;
}
if(p.val != q.val){
return false;
}
return symmetric(p.left, q.right) && symmetric(p.right,q.left);
}
左右对称的问题,使用递归的解法 (照镜子解法)
非递归解法
import java.util.Queue;
class Solution {
public boolean isSymmetric(TreeNode root) {
return symmetric(root, root);
}
public boolean symmetric(TreeNode u, TreeNode v) {
Queue <TreeNode> q = new LinkedList<TreeNode>();;
q.add(u);
q.add(v);
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;
}
}