gpt4 book ai didi

Tress DSA (Problem while running the code)(树DSA(运行代码时出现问题))

转载 作者:bug小助手 更新时间:2023-10-25 10:40:54 27 4
gpt4 key购买 nike



I am trying to find out the top view of a binary tree. The code is running correct on the custom test case but it shows different output on the same input whenever I tried to submit it. The platform is gfg.

我正在试着找出二叉树的俯视图。代码在自定义测试用例上运行正确,但每当我尝试提交时,它在同一输入上显示不同的输出。平台是GFG。


I have tried the following code and it is running correctly for most of the test cases.

我已经尝试了以下代码,并且它在大多数测试用例中都运行正常。


    def topView(self,root):

# code here

map = defaultdict(list)
queue = [[root , 0]]

while queue:

top , dim = queue.pop(0)
if not map[dim] :
map[dim] = top.data

if top.left:
queue.append([top.left, dim - 1])
if top.right:
queue.append([top.right,dim + 1])


map = dict(sorted(map.items()))
ans = []
for key in map:
ans.append(map[key])
return ans



更多回答

Please define “top view” with examples, and the test cases you’re having trouble with.

请用例子来定义“顶视图”,以及你遇到麻烦的测试用例。

优秀答案推荐

At the time of writing the GeeksforGeeks Python version for running individual tests (before submitting) is 3.7.17, but the version used to test your code when pressing Submit, is 3.5.2

在撰写本文时,用于运行单独测试(在提交之前)的GeeksforGeek Python版本是3.7.17,但用于在按下提交时测试代码的版本是3.5.2


This is crazy, but it explains why your code fails the tests being run on submission. Before 3.6 Python didn't guarantee a dict traversal order, and your code relies on insertion order when it does map = dict(sorted(map.items())). But before 3.6 this is useless, as the order of for key in map still is undetermined after that recreation of the dict.

这很疯狂,但它解释了为什么您的代码不能通过提交时运行的测试。在3.6之前的版本中,Python不能保证遍历字典的顺序,当它执行map=dict(sorted(map.Items()时,您的代码依赖于插入顺序。但在3.6版本之前,这是没有用的,因为在重新创建字典后,for key在地图中的顺序仍然是不确定的。


The fix is easy. Just don't recreate a dict at the end, but iterate the sorted pairs you get from calling sorted:

解决问题很容易。只是不要在最后重新创建字典,而是迭代通过调用sorted获得的排序对:


    ans = []
for key, val in sorted(map.items()):
ans.append(val)

NB: this is not the most efficient solution, but it is good enough to pass the tests.

注:这不是最有效的解决方案,但足以通过测试。


更多回答

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com