101. 对称二叉树 - 力扣(LeetCode)
思路:利用递归
- 确定递归函数的三要素:递归参数与返回值、递归出口、单层递归逻辑。
- 递归参数是两棵二叉树,一颗左子树,一颗右子树,返回值是布尔类型。
- 递归出口:当左子树为空且右子树不为空时,当右子树为空且左子树不为空时返回假。当左右子树都为空时返回真。当左右子树都不为空且左右子树的值不等时,返回假。
- 单层递归逻辑:左右子树都不为空且左右子树的值相等时:调用递归函数,判断左子树的左子树与右子树的右子树、左子树的右子树与右子树的左子树。
class Solution(object):def isSame(self,left,right):if left==None and right!=None:return Falseelif left!=None and right==None:return Falseelif left==None and right==None:return Trueelif left.val!=right.val:return Falseb1=self.isSame(left.left,right.right)b2=self.isSame(left.right,right.left)return b1 and b2def isSymmetric(self, root):if root==None:return Truereturn self.isSame(root.left,root.right)