题解
方法一 递归
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def isequ(left,right)->bool:
if not(left or right):
return True
if not(left and right):
return False
if left.val!=right.val:
return False
return isequ(left.left,right.right) and isequ(left.right,right.left)
return isequ(root.left,root.right)
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null){
return true;
}
return isSymmetric(root.left,root.right);
}
public boolean isSymmetric(TreeNode left,TreeNode right){
if(left==null && right==null){
return true;
}
if(left==null || right==null){
return false;
}
if(left.val!=right.val){
return false;
}
return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left);
}
}
方法二 迭代
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null||(root.left==null && root.right==null)){
return true;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root.left);
queue.offer(root.right);
while(!queue.isEmpty()){
TreeNode u=queue.poll();
TreeNode v=queue.poll();
if(u ==null && v==null){
continue;
}
if((u==null||v==null)||(u.val!=v.val)){
return false;
}
queue.offer(u.left);
queue.offer(v.right);
queue.offer(u.right);
queue.offer(v.left);
}
return true;
}
}