11. 盛最多水的容器
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
#从左往右逼近,如果左边小,则左边右移,否则右边左移
max_area=0
left=0
right=len(height)-1
while right>left:
max_area=max(max_area,(right-left)*min(height[right],height[left]))
if height[right]>height[left]:
left+=1
else:
right-=1
return max_area
102. 二叉树的层次遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
q=[root]
list=[]
while q:
temp_list=[]
for i in range(len(q)):
node=q.pop(0)
temp_list.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
list.append(temp_list)
return list
105. 从前序与中序遍历序列构造二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root=TreeNode(preorder[0])
left_len=inorder.index(preorder[0])
root.left=self.buildTree(preorder[1:left_len+1],inorder[:left_len]) #构建左子树
root.right=self.buildTree(preorder[left_len+1:],inorder[left_len+1:]) #构建右子树
return root
106. 从中序与后序遍历序列构造二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not inorder:
return None
root=TreeNode(postorder[-1])
m=inorder.index(postorder[-1])
root.left=self.buildTree(inorder[:m],postorder[:m])
root.right=self.buildTree(inorder[m+1:],postorder[m:-1])
return root