Python数据结构实战——数(Tree)

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()    #先建立树,再打印树

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值