[leetCode]剑指 Offer 28. 对称的二叉树
递归解法
一棵二叉树是对称的则其左右子树互为镜像,因此可以递归判断左右子树是否互为镜像来判断二叉树是否对称。
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode A, TreeNode B){
if(A == null && B == null) return true;
else if(A == null || B == null || (A.val != B.val))
return false;
else return isSymmetric(A.left, B.right) && isSymmetric(B.left, A.right);
}
}
迭代
使用队列将递归写法改成迭代。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while(!queue.isEmpty()){
TreeNode l = queue.poll();
TreeNode r = queue.poll();
if(l == null && r == null)
continue;
if(l == null || r == null)
return false;
if(l.val != r.val)
return false;
queue.offer(l.left);
queue.offer(r.right);
queue.offer(l.right);
queue.offer(r.left);
}
return true;
}
}