排序的二进制树
这是我用于BT的数组:
bt_array = [10, 3, 15, 1, None, 9]
这是我当前使用的代码。
def sorted_array(self): # NEEDS FIX
# TODO: should return a sorted array
elements=[]
if self.left:
elements += self.left.sorted_array()
elements.append(self.internal_array)
if self.right:
elements += self.right.sorted_array()
return elements
它返回了这一点:
sorted array [1, 3, None, 10, 9, 15]
但是我想按这样的smth来获取它:
sorted array [None, 1, 3, 9, 10, 15]
或者没有一个可以留在这里的地方,但是9应该在10之前。
This is the array I use for BT:
bt_array = [10, 3, 15, 1, None, 9]
This is the code I use currently.
def sorted_array(self): # NEEDS FIX
# TODO: should return a sorted array
elements=[]
if self.left:
elements += self.left.sorted_array()
elements.append(self.internal_array)
if self.right:
elements += self.right.sorted_array()
return elements
it returns this:
sorted array [1, 3, None, 10, 9, 15]
but I would like to get it in order smth like this:
sorted array [None, 1, 3, 9, 10, 15]
Or None can stay where it did, but 9 should be before 10.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输入
[10,3,15,1,none,9]
描述了此树:这不是有效的二进制 search 树。值9应该是3的正确孩子。由于输入是错误的,因此无法信任输出。如果预期这样的输入,则应验证树是有效的bst 。
此外,这种输入格式通常由代码挑战站点(例如LEET代码)使用,而
无
值仅用作用级别式遍历明确描述树的存根。这些无
值不应该包含在输出中。如果您的代码在
none
值中产生列表,则表示您创建了具有属性internal_array
的节点实例是none
。这样的节点不应存在于树上。这种属性被称为这种方式也令人困惑,因为它肯定应该不是将数组作为值,而是一个简单的数字。这是您可以使用的一些代码:
现在,对于您提供的示例输入,我们可以说它不是具有以下代码的有效BST:
如果我们纠正输入(更改9到11),我们可以使用上述<代码> __ iter __ 方法(类似于您的功能)以获取排序列表:
The input
[10, 3, 15, 1, None, 9]
describes this tree:This is not a valid binary search tree. The value 9 should have been a right child of 3. Since the input is wrong, the output cannot be trusted. If such input is expected, you should verify that a tree is a valid BST.
Moreover, this input format is typically used by code challenge sites (e.g. Leet Code), and the
None
values only serve as stubs to describe the tree unambiguously with a level-order traversal. TheseNone
values are not supposed to be included in the output.If your code produces a list with
None
values, then it means you created node instances that have an attributeinternal_array
that isNone
. Such nodes should not exist in the tree. It is also confusing that this attribute is called that way, as it should certainly not hold an array as value, but a simple number.Here is some code you could use:
Now for the example input you gave, we can tell that it is not a valid BST with the following code:
If we correct the input (changing 9 to 11), we can use the above
__iter__
method (similar to your function) to get the sorted list: