题目

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

image.png

思路

代码

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def isSymmetric(self, root: TreeNode) -> bool:
  9. def recur(L, R):
  10. if not L and not R: return True
  11. if not L or not R or L.val != R.val: return False
  12. return recur(L.left, R.right) and recur(L.right, R.left)
  13. return recur(root.left, root.right) if root else True