python:树数据结构
首先,树的抽象数据类型(ADT),它包括以下10个操作:
1.p.element( ):返回在位置p的元素
2.T.root( ): 如果树是空的,返回None,如果不空返回根结点
3. T.is_root§: 如果p是根结点返回True,否则返回False
4. T.parent§: 返回p点的双亲结点,如果p是根结点返回None,否则返回p的双亲结点
5.T.num_children§: 返回p结点的孩子数
6. T.children§: 生成位置p的一个迭代
7. T.is leaf§: 如果p是叶子结点返回True,否则返回False
8. len§: 返回树的结点树
9. T.is_empty( ): 如果T是空,返回True,否则,返回False
10. T.positions( ): 生产树T的所有位置的一个迭代
11. iter(T): 生产所有结点的一个迭代
第二,ADT的代码实现:
class Tree:
class Positon:
def element(self):
raise NotImplementError('This must be implemented by subclasss')
def __eq__(self,other):
raise NotImplementError('This must be implemented by subclass')
def __ne__(self,other):
return self==other
def root(self):
raise NotImplementError('This must be implemented by subclass')
def parnt(self,p):
raise NotImplementError('This must be implemented by subclass')
def num_children(self,p):
raise NotImplementError('This must be implemented by subclass')
def children(self,p):
raise NotImplementError('This must be implemented by subclass')
def __len__(self):
raise NotImplementError('This must be implemented by subclass')
def is_root(self,p):
return self.root()==p
def is_leaf(self,p):
return self.num_children(p)==0
def is_empty(self):
return len(self)==0
第三,树的深度和高度代码实现:
树的深度python代码实现:
def depth(self,p):
if self.is_root(p):
return 0
else:
return 1+self.depth(self.parent(p))
树的高度python代码实现:
代码1:
def _height1(self):
return max(self.depth(p) for p in self.positions() if self.is_leaf(p))
代码2:
def _height2(self,p):
if self.is_leaf(p):
return 0
else:
return 1+max(self._height2(c) for c in self.children(p))
用实例调用代码函数:
def height(self. p=None):
if p is None:
p=self.root()
return self._height2(p)