定义一:树由一组节点和一组连接节点的边组成。
树具有以下属性:
- 树的一个节点被指定为根节点。
- 除了根节点之外,每个节点 n 通过一个其他节点 p 的边连接,其中 p 是 n 的父节点。
- 从根路径遍历到每个节点路径唯一。
- 如果树中的每个节点最多有两个子节点,我们说该树是一个二叉树。
定义二: 树可以是空的,或者由一个根节点和零个或多个子树组成,每个子树也是一棵树。每个子树的根节点通过边连接到父树的根节点。 下图说明了树的这种递归定义。使用树的递归定义,我们知道下图中的树至少有四个节点,因为表示一个子树的每个三角形必须有一个根节点。 它可能有比这更多的节点,但我们不知道,除非我们更深入树。
代码实现:
class BinartTree:
def __init__(self, rootobject):
self.key = rootobject
self.leftchild = None
self.rightchild = None
def insertleft(self, newNode):
if self.leftchild == None:
self.leftchild = BinartTree(newNode)
else:
t = BinartTree(newNode)
t.leftchild = self.leftchild
self.leftchild = t
def insertright(self, newNode):
if self.rightchild == None:
self.rightchild = BinartTree(newNode)
else:
t = BinartTree(newNode)
t.rightchild = self.rightchild
self.rightchild = t
def getrightchild(self):
return self.rightchild
def getleftchild(self):
return self.leftchild
def setrootval(self, object):
self.key = object
def getrootval(self):
return self.key