freewheel笔试的一题(二叉树最小耗时)
刚做了笔试的大神们能帮忙看看哪里出错吗,只通过40%
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @param failId int整型 # @param timeCost int整型一维数组 # @return int整型 # class Solution: def GetMinTimeCost(self , root , failId , timeCost ): # write code here if not root: return 0 #首先根据编码找到fail节点:节点标号从0开始,节点编码唯一且连续 def preorder(root,failid): if not root: return None if root.val==failid: return root else: preorder(root.left,failid) preorder(root.right,failid) a=preorder(root, failId) if not a: return 0 def cost(root,timeCost,res): #应该是每一步都要求是最小的 queue=[root] while queue: n=len(queue) l=[] for i in range(n): tmp=queue.pop(0) if tmp.left==None and tmp.right==None: continue if tmp.left or tmp.right: l.append(timeCost[tmp.val]) if tmp.right: queue.append(tmp.right) if tmp.left: queue.append(tmp.left) if not l: res+=0 else: res+=min(l) return res h=cost(a,timeCost,0) return h