快要毕业了但是代码能力实在是太差了,想要刷leetcode但是发现,自己连树的python都无法实现,万事开头难,做一些学习和记录。
创建一棵树
class BinaryTree:
def __init__(self,rootvalue):
self.rootvalue = rootvalue
self.leftchild = None
self.rightchild = None
注意对于非常小白的小白而言,需要了解Python中的类以及类中__init__
的用法,其次要了解树的结构,可参考木水的文章,本篇文章也是在此基础上分享一些自己的想法和学到的经验,与大家一起学习进步~
创建左右子树
def Insertleft(self,newvalue):
if self.leftchild == None:
self.leftchild = BinaryTree(newvalue)
else:
t = BinaryTree(newvalue)
t.leftchild = self.leftchild
self.leftchild = t
def Insertright(self,newvalue):
if self.rightchild == None:
self.rightchild = BinaryTree(newvalue)
else:
t = BinaryTree(newvalue)
t.rightchild = self.rightchild
self.rightchild = t
我的代码其实并不是十分规范,参考之后要自己上手进行练习,在插入左右子树之前需要对节点的左右子树是否为空进行判断,两者的插入方式并不相同。用t来先创立以新的插入值创建的子树即t = BinaryTree(newvalue)
可能你并不明白我在说什么,自己上手简单编程即可明白。
树的维护
树应当具有基本功能,查询左右子树,查询值和更新值。
def getRightchild(self):
return self.rightchild
def getLeftchild(self):
return self.leftchild
def getrootvalue(self):
return self.rootvalue
def setrootvalue(self,value):
self.rootvalue = value
简单练习体验
a = BinaryTree('1')
a.Insertleft('l')
a.Insertright('R')
print(a.getrootvalue(),a.getLeftchild().rootvalue,a.rightchild)
a.Insertleft('L')
print(a.getLeftchild().rootvalue,a.getLeftchild().getLeftchild().rootvalue)
结果
1 l <__main__.BinaryTree object at 0x00000218ACFED748>
L l
进程已结束,退出代码 0
会发现其实如果想要得到节点的值,既可以用a.getrootvalue()
,也可以用a.rootvalue
,注意后面一种是没有括号()的。在使用的过程中时刻牢记使用的是树结构,调用的是值还是函数,否则会很混乱。