python - 无法添加 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,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
. 你能指出错误在哪里吗?
解决方案
def attachRightSub(self,Binarytree):
global BinaryTree
self.root.rightchildnode = BinaryTree
BinaryTree = None
应该
def attachRightSub(self,BinaryTree):
self.root.rightchildnode = BinaryTree.root
你正在做的是删除你原来的BinaryTree
类。
推荐阅读
- python-3.x - Python中返回值的混淆
- javascript - 需要遍历具有对象 Vue 的数组
- jquery - 如何修复 Uncaught SyntaxError: Unexpected identifier and Invalid left-hand side in assignment errors when using jquery.i18n.propeties plugin
- c# - .net core 2.2 数据库连接错误完整堆栈跟踪
- mysql - 为多对多关系创建mysql视图
- asp.net - WCF 中如何生成 WSSE UsernameToken Id
- python - ModuleNotFoundError:没有名为“预处理器”的模块
- android - TensorFlow Lite - 对象检测 API YOLOv3
- excel - 抓取谷歌地图目的地
- matlab - 使用 fminsearch 进行参数估计