python---节点

-'''
1.根据当前节点获取父节点
2.根据当前节点获取所有子节点
3.根据当前节点获取所有祖先节点
4.根据当前节点获取所有子孙节点
5.根据当前节点获取所有兄弟节点
'''
class Tree:
childToParent=None
parentTochild=None
def add(self,parent,child):
if self.childToParent is None:
self.childToParent={child:parent}
else:
self.childToParent[child]=parent
if self.parentTochild==None:
self.parentTochild={parent:[]}
children=self.parentTochild.get(parent,[])
if len(children)==0:
self.parentTochild[parent]=children
children.append(child)
def getParent(self,child):
return self.childToParent.get(child,'没有父节点')
def getChildren(self,parent):
return self.parentTochild.get(parent,'没有下级')
def getZuxian(self,zisun):
'''
思想就是递归问爹
1.可以获取上一级的 getParent
2.如果能够让上一级返回的数据再执行 getParent 一次类推直到没有上级 终止
:param zisun:
:return:
'''
parent=self.getParent(zisun)
if parent is None:
return []
zupu=self.getZuxian(parent)
zupu.append(parent)
return zupu
def zisun(self,zs,zu):
'''
1.得到当前节点的下级
2.遍历当前节点的下级,每一个下级的孩子去得到他们的孩子
:param zs:结果
:param zu:条件
:return:
'''
children=self.getChildren(zu)
if children == '没有下级':
return
for c in children:
self.zisun(zs,c)
zs.extend(children)
def getSibling(self,sibling):
parent=self.getParent(sibling)
children=self.getChildren(parent)
children.remove(sibling)
return children
if __name__=='__main__':
tree=Tree();
tree.add(None,'学校')
tree.add('学校','商学院')
tree.add('学校','电子学院')
tree.add('学校','计算机学院')
tree.add('计算机学院','软件')
tree.add('计算机学院','网络')
tree.add('计算机学院','数据')
tree.add('网络','网一')
tree.add('网络','网二')
tree.add('网络','网三')
#根据当前节点获取父节点
child='网三'
parent=tree.getParent(child)
print('{0}的上级是:{1}'.format(child,parent))
# 根据当前节点获取所有子节点
parent='网三'
children=tree.getChildren(parent)
print('{0}的子级是:{1}'.format(parent,children))
#根据当前节点获取所有祖先节点
zisun='网三'
zuxian=tree.getZuxian(zisun)
print('{0}的祖先是:{1}'.format(zisun,zuxian))
#4.根据当前节点获取所有子孙节点
zu='网三'
zs=[]
tree.zisun(zs,zu)
print('{0}的子孙是{1}'.format(zu,zs))
# 5.根据当前节点获取所有兄弟节点
sibling='网三'
rs=tree.getSibling(sibling)
print('{0}的兄弟是:{1}'.format(sibling,rs))

猜你喜欢

转载自blog.csdn.net/weixin_42067855/article/details/80629835
今日推荐