此题可以分为递归和迭代两种写法,这里暂时只给出递归法:
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)
(看到备注了,这道题必须拿下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
Leetcode刷题10.20——对称二叉树 & 翻转二叉树
原文:https://www.cnblogs.com/nekoneko-15/p/13855487.html