Python 从字典构造多叉树

这篇博客介绍了如何使用Python构建多叉树结构。首先定义了一个TreeNode类,包含节点值和子节点列表。然后通过深度优先搜索(DFS)方法从字典中构建多叉树。最后,提供了两种打印方法,一种按字典格式输出,另一种按层级结构展示。示例展示了如何将给定字典转换为多叉树并打印输出。
摘要由CSDN通过智能技术生成

Python 从字典构造多叉树


题目要求

构造一个树节点类,每个节点都有一个int类型的值(val),和0个或多个子节点childs。
给定一个字典,其中字典的key为当前节点的val,value对应列表对应当前节点的childs的val值。

请将该字典的构造为多叉树结构,使用root表示数的根节点,并打印每个节点的值及其子节点的值。(这里确保OrderDict字典的第一个key为树的根节点)。

输入:

{
    1: [2, 3, 4],
    2: [5, 6],
    3: [7],
    7: [8, 9, 10],
}

在这里插入图片描述


代码实现

from collections import defaultdict


class TreeNode(object):
    def __init__(self, val=None) -> None:
        self.val = val
        self.childs = []

    def add_childs(self, child: "TreeNode"):
        self.childs.append(child)

    def __repr__(self) -> str:
        return str(self.val)

    @classmethod
    def build_tree(cls, input_dict: dict):

        # 深度优先遍历构造多叉树结构
        def dfs(node, input_dict):
            if node.val in input_dict:  # 当前节点还有子节点时,继续对每个child向下构造
                for val in input_dict[node.val]:
                    cur_node = TreeNode(val)
                    dfs(cur_node, input_dict)
                    node.add_childs(cur_node)
            else:  # 当前节点没有子节点,直接返回
                return

        # 获取字典的第一个key,并以此为根节点构造多叉树
        root = TreeNode(list(input_dict.keys())[0])
        dfs(root, input_dict)

        return root

    @classmethod
    def print_tree(cls, root: "TreeNode"):
        """按照字典输入形式打印输出"""
        if root:
            if root.childs:
                print(root.val, ": ", end="")
                print('[%s]' % (' '.join([str(_.val) for _ in root.childs])))
                for node in root.childs:
                    cls.print_tree(node)
            else:
                print(root.val, ": []")

    @classmethod
    def print_tree_graph(cls, root: "TreeNode"):
        """按照树的层级打印输出"""
        node_with_level = defaultdict(list)
        node_with_level[0].append([root])
        cur_level = 0

        while node_with_level:
            # 打印当前层节点
            cur_nodes_lists = node_with_level.pop(cur_level)
            for nodes_list in cur_nodes_lists:
                print(nodes_list, end=" ")

                for node in nodes_list:  # 如果还有子节点,将其添加到下一层
                    if node.childs:
                        node_with_level[cur_level + 1].append(node.childs)
                    else:  # 没有子节点的话,使用[]占位
                        node_with_level[cur_level + 1].append([])
            cur_level += 1
            print()


input_dict = {
    1: [2, 3, 4],
    2: [5, 6],
    3: [7],
    7: [8, 9, 10],
}

tree = TreeNode.build_tree(input_dict)
TreeNode.print_tree(tree)
TreeNode.print_tree_graph(tree)

运行结果:

# print_tree方法输出字典格式结果:
1 : [2 3 4]
2 : [5 6]
5 : []
6 : []
3 : [7]
7 : [8 9 10]
8 : []
9 : []
10 : []
4 : []

# print_tree_graph方法输出类似数层级结构格式的结果:
[1] 
[2, 3, 4] 
[5, 6] [7] [] 
[] [] [8, 9, 10] 
[] [] []

对于第二种输出格式,其关系为:

           +---+
           | 1 |
           +-+-+
             |
             |
       +---+-v-+---+
  +----+ 2 | 3 | 4 +--+
  |    +---+-+-+---+  |
  |          |        |
  |          |        |
+-v-+---+   +v--+   +-v+
| 5 | 6 |   | 7 |   |  |
+-+-+--++   +-+-+   +--+
  |    |      |
  |    |      |
+-v+  +v-+  +-v-+---+---+
|  |  |  |  | 8 | 9 | 10|
+--+  +--+  ++--+-+-+--++
             |    |    |
             |    |    |
            +v-+ +v-+ +v-+
            |  | |  | |  |
            +--+ +--+ +--+

在这里插入图片描述

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值