- 将有序数组转换为二叉搜索树(LeetCode第108题)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
numsLen = len(nums)
midIndex = numsLen // 2
root = TreeNode(nums[midIndex])
root.left = self.sortedArrayToBST(nums[:midIndex]) #比root小的放在左子树
root.right = self.sortedArrayToBST(nums[midIndex+1:]) #比root大的放在右子树
return root
- 平衡二叉树(LeetCode第110题)
方法一:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
def maxDepth(root):
if not root:
return 0
lDepth = maxDepth(root.left)
rDepth = maxDepth(root.right)
if abs(lDepth - rDepth) > 1:
self.flag = False
return max(lDepth,rDepth) + 1
maxDepth(root)
if self.flag == False:
return False
else:
return True
方法二:利用之前判定二叉树最大深度的函数
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
elif abs(self.height(root.left)-self.height(root.right))>1: #就是root.left和root.right往下的深度
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def height(self,root):
if root == None:
return 0
else:
return max(self.height(root.left),self.height(root.right))+1
- 二叉树的最小深度(LeetCode第111题)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left == None and root.right == None:
return 1
elif root.left == None:
return 1 + self.minDepth(root.right)
elif root.right == None:
return 1 + self.minDepth(root.left)
else:
return 1 + min(self.minDepth(root.left),self.minDepth(root.right))
- 路径总和(LeetCode第112题)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
sum -= root.val
if sum == 0:
if root.left is None and root.right is None:
return True
return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)