腾讯音乐9.8笔试
一道字符串+两道二叉树题目。感觉有点难
第一道60%。
第二题100%。
第三题55%。
第二题 100%
def getBinaryTrees(self , preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: # write code here ret = [] def buildTree(preorder,inorder): if len(preorder)==0: return [None] x = preorder.pop(0) tree_list = [] for i,val in enumerate(inorder): if val==x: l_trees = buildTree(preorder[:i],inorder[:i]) r_trees = buildTree(preorder[i:],inorder[i+1:]) for l in l_trees: for r in r_trees: root = TreeNode(x) root.left,root.right = l,r tree_list.append(root) return tree_list ret = buildTree(preOrder,inOrder) return ret第三题 55%
def getTreeSum(self , tree: TreeNode) -> int: # write code here MOD = 10**9+7 def dfs(node): if not node: return 0 left = dfs(node.left) right = dfs(node.right) total = 1 if left==right: total = (total+left+right)%MOD elif left>right: total = (total+left*2)%MOD else: total = (total+right*2)%MOD return total%MOD res = dfs(tree) return res第三题有无大佬指正一下正确解法