【问题标题】:How to convert a dictionary of nodes into a binary tree? [Python]如何将节点字典转换为二叉树? [Python]
【发布时间】:2018-12-29 21:42:36
【问题描述】:

我有一个对象字典,其中包含键 [Node Value] 及其左右节点的列表。 示例字典:

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

我的示例节点类:

class Node:
    def __init__(self,key):
        self.left = None
        self.right = None
        self.val = key

如何将字典转换成二叉树?

【问题讨论】:

标签: python tree binary


【解决方案1】:

你可以使用递归:

class Tree:
  def __init__(self, _val = None):
    self.val = _val
    self.right, self.left = None, None
  def __iter__(self):
    yield self.val
    yield from [[], self.left][bool(self.left)]
    yield from [[], self.right][bool(self.right)]
  def _insert_vals(self, _start, _d):
    self.val = _start
    for a, b in zip(['left', 'right'], _d.get(_start, [])):
      if b is not None:
        setattr(self, a, Tree())
        getattr(self, a)._insert_vals(b, _d)

d = {1: [2, 3], 2: [4, 0], 3: [None, 5], 4: [6, None], 5: [None, 7], 6: [8, None], 7: [None, 9], 8: [None, None], 9: [None, None]}
t = Tree()
t._insert_vals(1, d)
print([i for i in t])

输出:

[1, 2, 4, 6, 8, 0, 3, 5, 7, 9]

编辑:更短:

class Tree:
  def __init__(self, _val, _r, _d):
    self.v, self.right, self.left = _val, None, None
    if _r:
       l, r = _r
       self.left, self.right = Tree(l, _d.get(l, []), _d), Tree(r, _d.get(r, []), _d)
t = Tree(1, d[1], d)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-02-28
    • 2019-04-14
    • 2021-06-07
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多