作业1
要求:最长路径:给定一个节点值为整数的二叉树,计算最长的同值路径。同值指的是路径中的所有节点值相同,路径长度等于路径中的节点数-1.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def longestPath(root):
if not root:
return 0
res = [0]
def dfs(tree):
if not tree:
return 0
left_len, right_len = dfs(tree.left), dfs(tree.right)
if tree.left and tree.left.val == tree.val:
left = left_len + 1
else:
left = 0
if tree.right and tree.right.val == tree.val:
right = right_len + 1
else:
right = 0
res[0] = max(res[0], left + right)
return max(left, right)
dfs(tree)
return res[0]
tree = TreeNode(1, TreeNode(1, TreeNode(1)), TreeNode(1))
print(longestPath(tree))
tree = TreeNode(3, TreeNode(2, TreeNode(1), TreeNode(2)), TreeNode(3, None, TreeNode(3)))
print(longestPath(tree))
tree = TreeNode(3, TreeNode(2, TreeNode(2), TreeNode(2)), TreeNode(4, None, TreeNode(4)))
print(longestPath(tree))
作业2. 数组连乘:给定一个整数数组A=[a0, a1, …, an-1],计算数组中乘积最大的连续子数组B=[ai, ai+1, …, aj]
def subArrayMul(a):
if not a:
return 0
ans = a[0]
pre_max = a[0]
pre_min = a[0]
for num in a[1:]:
cur_max = max(pre_max * num, pre_min * num, num)
cur_min = min(pre_max * num, pre_min * num, num)
ans = max(cur_max, ans)
pre_max = cur_max
pre_min = cur_min
return ans
a1 = [4, 3, 1, 10, -1, 10, 1, -2, 5, -5, 3, 4]
print(subArrayMul(a1))
a2 = [1, 2, -2, 5, -1, -1, 5, 4]
print(subArrayMul(a2))
a3 = [2, -2, -1, 10, -1, -5, 4]
print(subArrayMul(a3))