迭代
class Solution {public boolean isSymmetric(TreeNode root) {if(root==null){return true;}Deque<TreeNode> de=new LinkedList<>();TreeNode l,r;int le;de.offer(root.left);de.offer(root.right);while(!de.isEmpty()){l=de.pollFirst();r=de.pollLast();if(l==null&&r==null){continue;}if((l!=null&&r==null)||(l==null&&r!=null)||l.val!=r.val){return false;}if(l!=null&&r!=null){de.offerFirst(l.left);de.offerFirst(l.right);de.offerLast(r.right);de.offerLast(r.left);}}return true;}
}
class Solution(object):def isSymmetric(self, root):if root is None:return Truede=collections.deque()de.append(root.left)de.append(root.right)while de:l=de.popleft()r=de.pop()if l is None and r is None:continueif (l is None and r) or (l and r is None) or l.val!=r.val:return Falseif l and r:de.appendleft(l.left)de.appendleft(l.right)de.append(r.right)de.append(r.left)return True
递归(本方法非原创,来自代码随想录)
//本方法非原创,来自https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
class Solution {public boolean isSymmetric(TreeNode root) {if(root==null){return true;}return Compare(root.left,root.right);}private boolean Compare(TreeNode left, TreeNode right) {if(left==null&&right!=null){return false;}if(left!=null&&right==null){return false;}if(left==null&&right==null){return true;}if(left.val!=right.val){return false;}// 比较外侧boolean compareOutside=Compare(left.left,right.right);// 比较内侧boolean compareInside=Compare(left.right,right.left);return compareOutside && compareInside;}
}
#本方法非原创,来自https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
class Solution(object):def isSymmetric(self, root):if root is None:return Truedef Compare(left,right):if left is None and right:return Falseif left and right is None:return Falseif left is None and right is None:return Trueif left.val!=right.val:return False;#比较外侧compareOutside=Compare(left.left,right.right)#比较内侧compareInside=Compare(left.right,right.left)return compareOutside and compareInsidereturn Compare(root.left,root.right)