获取二叉树中和最大的路径 【leetcode124】
二叉树每一个节点都有一个数,求和最大的路径。
注意:这是所有路径,包括一个叶子节点到另一个叶子节点的路径。
def recursion ( root, m) :
if root is None :
return 0
left = recursion( root. left, m)
right = recursion( root. right, m)
ret = max ( left, right, 0 ) + root. val
m[ 0 ] = max ( m[ 0 ] , ret, left+ right+ root. val)
return ret
def maxPathSum ( root) :
if root is None :
return 0
m = [ root. val]
recursion( root, m)
return m[ 0 ]
二叉树的最小深度与最大深度 【leetcode111、104】
def minDepth ( root) :
if root is None :
return 0
if root. left is not None :
if root. right is not None :
return min ( minDepth( root. left) , minDepth( root. right) ) + 1
else :
return minDepth( root. left) + 1
elif root. right is not None :
return minDepth( root. right) + 1
else :
return 1
def maxDepth ( root) :
return 0 if root is None else max ( maxDepth( root. left) , maxDepth( root. right) ) + 1
判断二叉树是否平衡 【leetcode110】
每个节点的左子树与右子树的高度之差至多为1则是平衡二叉树。
def recursion ( root, h) :
if root is None :
h[ 0 ] = 0
return True
lh, rh = [ 0 ] , [ 0 ]
if not recursion( root. left, lh) :
return False
if not recursion( root. right, rh) :
return False
h[ 0 ] = max ( lh[ 0 ] , rh[ 0 ] ) + 1
return abs ( lh[ 0 ] - rh[ 0 ] ) <= 1
def isBalanced ( root) :
return recursion( root, [ 0 ] )
判断两个二叉树是否相同 【leetcode100】
def isSame ( root1, root2) :
if root1 is None :
return root2 is None
else :
if root2 is None :
return False
else :
return root1. val == root2. val and isSame( root1. left, root2. left) and isSame( root1. right, root2. right)
判断二叉树是否对称 【leetcode101】
def recursion ( root1, root2) :
if root1 is None :
return root2 is None
else :
if root2 is None :
return False
else :
return root1. val == root2. val and recursion( root1. left, root2. right) and recursion( root2. left, root1. right)
def isSymmetrical ( root) :
if root is None :
return True
return recursion( root. left, root. right)
判断二叉树是否为二叉搜索树 【leetcode98、173】
对于任意一个节点,其左子树比它小,其右子树比它大
def inorderTraversal ( root, arr) :
if root is not None :
inorderTraversal( root. left, arr)
arr. append( root. val)
inorderTraversal( root. right, arr)
def isSearchTree ( root) :
arr = [ ]
inorderTraversal( root, arr)
i = 1
while i < len ( arr) :
if arr[ i- 1 ] >= arr[ i] :
return False
i += 1
return True