如何解决无法添加BinarySubTree
仅当节点连接到树的左或右分支时,它才有效。但是,当要将节点附加到子树时,事实证明它没有成功添加。这是代码:
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,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
。您能指出错误在哪里吗?
解决方法
def attachRightSub(self,Binarytree):
global BinaryTree
self.root.rightchildnode = BinaryTree
BinaryTree = None
应该是
def attachRightSub(self,BinaryTree):
self.root.rightchildnode = BinaryTree.root
您正在做的是删除原始的BinaryTree
类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。