【问题标题】:Cannot add BinarySubTree无法添加 BinarySubTree
【发布时间】:2020-10-25 10:08:56
【问题描述】:

只有当节点连接到树的左分支或右分支时,它才能正常工作。但是当涉及到将节点附加到子树时,事实证明它没有成功添加。代码如下:

class BinaryTree():
    class BinaryTreeNode():
        def __init__(self,leftchildnode,rightchildnode,item):
            self.leftchildnode = leftchildnode
            self.rightchildnode = rightchildnode
            self.item = item

    def __init__(self):
        self.root = None
    
    def setRoot(self,item):
        self.cur = self.BinaryTreeNode(None,None,item)
        self.root = self.cur

    def attachLeft(self,item):
        self.left = self.BinaryTreeNode(self.root.leftchildnode,None,item)
        self.root.leftchildnode = self.left

    def attachRight(self,item):
        self.right = self.BinaryTreeNode(None,self.root.rightchildnode,item)
        self.root.rightchildnode = self.right

    def attachLeftSub(self,Binarytree):
        global BinaryTree
        self.root.leftchildnode = BinaryTree
        BinaryTree = None
    
    def attachRightSub(self,Binarytree):
        global BinaryTree
        self.root.rightchildnode = BinaryTree
        BinaryTree = None

    def inorderdisplay(self):
        self.recursive_inorder_display(self.root)

    def recursive_inorder_display(self,BinaryTreeNode):
        if BinaryTreeNode != None:
            self.recursive_inorder_display(BinaryTreeNode.leftchildnode)
            print(BinaryTreeNode.item)
            self.recursive_inorder_display(BinaryTreeNode.rightchildnode)

tree = BinaryTree()
tree.setRoot("J")
tree1 = BinaryTree()
tree1.setRoot("D")
tree1.attachLeft("E")
tree1.attachRight("F")
tree2 = BinaryTree()
tree2.setRoot("G")
tree2.attachLeft("H")
tree2.attachRight("I")
tree.attachLeftSub(tree1)
tree.attachLeftSub(tree2)
tree.inorderdisplay()

它应该按顺序显示所有项目,但 I 得到的唯一项目是 J。你能指出错误在哪里吗?

【问题讨论】:

    标签: python data-structures binary-tree


    【解决方案1】:
    def attachRightSub(self,Binarytree):
        global BinaryTree
        self.root.rightchildnode = BinaryTree
        BinaryTree = None
    

    应该是

    def attachRightSub(self,BinaryTree):
        self.root.rightchildnode = BinaryTree.root
    

    你正在做的是删除你原来的 BinaryTree 类。

    【讨论】:

    • 原来另一个错误是 AttributeError: type object 'BinaryTree' has no attribute 'leftchildnode' at the inorder display part.我的订单代码错了吗?
    • 在显示错误之前是否打印任何数据?
    • 啊,我明白了,我弄错了,你应该附上BinaryTree.root;我会更正答案。
    • 嗯,它说 AttributeError: type object 'BinaryTree' has no attribute 'root'
    • 请注意您的原始函数 (Binarytree) 和我的答案 (BinaryTree) 之间的大小写差异
    猜你喜欢
    • 2013-09-14
    • 2019-06-13
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多