如何将节点字典转换为二叉树? [蟒蛇]

时间:2018-07-22 03:40:54

标签: python tree binary

我有一个对象字典,它由键[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

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

1 个答案:

答案 0 :(得分:0)

您可以使用递归:

postman

输出:

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]