Leetcode刷题10.20——对称二叉树 & 翻转二叉树

leetcode 101 对称二叉树 

  此题可以分为递归和迭代两种写法,这里暂时只给出递归法:

  • 注意递归函数的作用是:判断两个根节点下的子树是不是镜像对称的
  • 函数的输入是:两个根节点
  • 函数的输出是:布尔值
  • 注意不能够在给出的函数模板中直接写递归,要新建一个两个 输入参数的递归函数
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        else:
            def isMirror(root1, root2):
                if not root1 and not root2:    # 先判断存在——都不存在
                    return True
                elif not root1 or not root2:   # 先判断存在——有一个不存在
                    return False
                elif root1.val != root2.val:   # 存在后先判断当前两个根节点的值是否相等
                    return False
                else:
                    return isMirror(root1.right, root2.left) and isMirror(root1.left, root2.right)
        return isMirror(root, root)

leetcode 226 翻转二叉树

   (看到备注了,这道题必须拿下hhhh)

  翻转二叉树,此题也暂时给出递归解法,其他的解法后续做明白了再补充。非常简单的代码,但是可能有点不好理解。此处给出一个我认为讲的特别好的题解,捋清楚了递归函数的思想:递归函数怎么写?本文帮你理解递归

  • 主要是明确该函数的作用(干了什么)、输入以及输出分别是什么。
  • 另外一定要注意交换两个节点时一定要用下面代码中的写法,不能用新的变量交换。
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:  
        # 函数作用:交换他的左右子树
        # 函数输出:交换后的左右子树根节点
        # 函数输入:待交换的根节点
        if not root:
            return 
        else:
            L = root.left
            R = root.right
            root.left, root.right = self.invertTree(R), self.invertTree(L)
        return root
原文地址:https://www.cnblogs.com/nekoneko-15/p/13855487.html