1.实验目标
构建一颗如下图所示的树:
2.定义树类
class TreeNode:
def __init__(self, data):
self.data = data #树的值
self.children = [] #树的孩子结点
self.parent = None #树的父结点
def get_level(self): #划分层级
level = 0
p = self.parent #p为父结点
while p: #如果父结点存在
level += 1
p = p.parent #p移向父结点
return level #返回当前层级
def print_tree(self):
spaces = ' '*self.get_level()*3 #根据层级打印空格
prefix = spaces + "|__" if self.parent else "" #如果没有父结点则不需要打印
print(prefix + self.data)
if self.children:
for child in self.children: #递归
child.print_tree()
def add_child(self, child):
child.parent = self #要添加的父结点是self
self.children.append(child) #父结点self的children添加child
3.构建树并打印
def build_product_tree():
root = TreeNode("Electronics") #实例化root
laptop = TreeNode("Laptop")
laptop.add_child(TreeNode("Mac")) #父结点是laptop
laptop.add_child(TreeNode("Surface"))
laptop.add_child(TreeNode("Thinkpad"))
cellphone = TreeNode("Cell Phone")
cellphone.add_child(TreeNode("iphone"))
cellphone.add_child(TreeNode("Google Pixel"))
cellphone.add_child(TreeNode("vivo"))
tv = TreeNode("TV")
tv.add_child(TreeNode("Samsung"))
tv.add_child(TreeNode("LG"))
root.add_child(laptop)
root.add_child(cellphone)
root.add_child(tv)
root.print_tree() #打印树
4.显示结果
build_product_tree() #先建立树,再打印树