问题遇到的现象和发生背景
左右子树已经有插入但是没打印出来
用代码块功能插入代码,请勿粘贴截图
1.用pycharm自带的类
from pythonds.trees import BinaryTree
r = BinaryTree('a')
r.getRootVal()
print(r.getRootVal())
r.insertLeft('b')
print(r.getLeftChild())
r.insertRight('c')
r.insertRight('e')
print(r.getRightChild)
2.编写的类
# 面向对象编程:定义一个树类
class BinaryTree():
def init(self, rootobj):
self.key = rootobj
self.leftchild = None
self.rightchild = None
def insertleft(self, newnode):
if self.leftchild == None:
self.leftchild = BinaryTree(newnode) # ?
else:
t = BinaryTree(newnode)
t.leftchild = self.leftchild
self.leftchild = t
return r
def insertright(self, newnode):
if self.rightchild is None:
self.rightchild = BinaryTree(newnode)
else:
t = BinaryTree(newnode) # BinaryTree(newnode), self.rightchild = self.rightchild, BinaryTree(newnode)
t.rightchild = self.rightchild #错误的:需要创造BinaryTree()
self.rightchild = t
return r
# 二叉树的访问函数
def getrootval(self):
return self.key
def setrootval(self, obj):
self.key = obj
def getleftchild(self):
return self.leftchild
def getrightchild(self):
return self.rightchild
这两种都不能实现左右子树的扩增
运行结果及报错内容
Connected to pydev debugger (build 213.6777.50)
a
<pythonds.trees.binaryTree.BinaryTree object at 0x0000020FD7E30DF0>
<bound method BinaryTree.getRightChild of <pythonds.trees.binaryTree.BinaryTree object at 0x0000020FD7E48C70>>
Process finished with exit code 0
我想要达到的结果
成功打印我的对左右子树的扩列