226.翻转二叉树
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
101. 对称二叉树
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self, left, right):
if left == None and right != None: return False
elif left != None and right == None: return False
elif left == None and right == None: return True
elif left.val != right.val: return False
outside = self.compare(left.left, right.right)
inside = self.compare(left.right, right.left)
isSame = outside and inside
return isSame
104.二叉树的最大深度
class Solution:
def maxdepth(self, root: treenode) -> int:
return self.getdepth(root)
def getdepth(self, node):
if not node:
return 0
leftheight = self.getdepth(node.left)
rightheight = self.getdepth(node.right)
height = 1 + max(leftheight, rightheight)
return height
111.二叉树的最小深度
class Solution:
def getDepth(self, node):
if node is None:
return 0
leftDepth = self.getDepth(node.left)
rightDepth = self.getDepth(node.right)
if node.left is None and node.right is not None:
return 1 + rightDepth
if node.left is not None and node.right is None:
return 1 + leftDepth
result = 1 + min(leftDepth, rightDepth)
return result
def minDepth(self, root):
return self.getDepth(root)