二叉树的最大深度
题目:给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
方法1:递归
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
将有序数组转换为二叉搜索树
题目:将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
对称二叉树
方法1:递归
def is_symmetric(root):
return is_mirror(root, root)
def is_mirror(t1, t2):
if t1 == None and t2 == None:
return True
if t1 == None or t2 ==None:
return False
return t1.val ==t2.val \
and is_mirror(t1.right, t2.left) \
and is_mirror(t1.left, t2.right)
方法2:迭代