【问题标题】:Traversing a BST in an in-order fashion and storing the nodes in an array, but the output is not sorted?以有序方式遍历 BST 并将节点存储在数组中,但输出未排序?
【发布时间】:2022-01-25 01:27:15
【问题描述】:

我在in-order manner 中遍历Binary Tree 以确定它是否是Binary Search Tree。这是我的代码:

class T:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def is_bst(node):  
    if not node:
        return 

    output = []
    
    is_bst(node.left)
    output.append(node.value) 
    is_bst(node.right)
    print(output)

对于上面的例子,output = [1,3,2,9,7,5]

但这显然是不正确的! - 我通常会调试,但我不熟悉运行树/二叉树作为输入。知道我的代码哪里出错了吗???


更新代码:

class T:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

        
def inOrderTraversal(node,output): 
        if not node: 
            return None
        
        is_bst(node.left)
        output.append(node.value) 
        is_bst(node.right)
        return 
    
def is_bst(node):  
    
    output = []
    
    inOrderTraversal(node,output)
    
    print(output)

同样的例子,output = [1,3,2,9,7,5] 仍然是错误的

【问题讨论】:

  • 请不要不要在问题得到答复后更改其基本部分。通过这种方式,您可以做出有效的答案或 cmets 看起来完全偏离主题。此外,您使您的问题对社区毫无用处——未来的读者将无法理解实际问题是什么,因此他们将无法从 cmets 和给出的答案中学习。如果您想分享您的进度,请不要替换您之前的问题,而是向其中添加新信息,或发布新问题。
  • 了解 Cia,我将在未来创建一个新问题或添加到它。谢谢
  • 我已编辑您的问题以显示原始代码和更新版本。

标签: python binary-tree


【解决方案1】:

您在例程中创建您的output,因此它始终为空。然后添加当前节点的值,但在例程结束时打印它。结果是 postorder,而不是 inorder - 每个节点都打印在 它的两个子树之后。

除了代码结构之外,您的函数名称错误 - 实际上您不希望它回答树是否是 BST,您只希望它返回内容:

def dump_tree_inorder(node, output):  
    if not node:
        return 
    
    dump_tree_inorder(node.left, output)
    output.append(node.value) 
    dump_tree_inorder(node.right, output)

【讨论】:

  • 嗨 CiaPan;你的意思是我应该创建一个辅助函数来运行递归,并且输出 = [] 将位于主函数中?
  • 是的 - 如果你想累积整个列表,这是正确的方法。
  • 让我修改代码 - 我尝试这样做,但结果相同! - 让我改变它
  • 现在输出更糟了... [] [] [1] [] [] [3] [2] [] [] [] [9] [7] [5]跨度>
  • @Patrick_Chong 请查看扩展答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多