繁体   English   中英

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

[英]How to convert a dictionary of nodes into a binary tree? [Python]

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

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

您可以使用递归:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM