如何使用字典创建二叉树?

时间:2019-03-30 15:56:41

标签: python binary-tree

我想根据父母(键)及其子(值,以元组(one_child,second_child)的值)的字典创建二叉树:

{1:(2,3), 2:(4,5), 4:(6, None), 3:(7,8), ...}   #they are in random order

应在不使用递归的情况下创建二叉树。

我的Node类:

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

我想要的是: 我尝试过的是:

self.root = self.Node(found_root)
parents = list(dictionary)
p = 0
while (p != len(parents)-1):
    curr_node = self.Node(parents[p], self.Node(dictionary.get(parents[p])[0]),self.Node(dictionary.get(parents[p])[1]))
    p += 1

1 个答案:

答案 0 :(得分:0)

您可以在Node类中创建自定义插入方法,然后可以通过对字典进行简单的迭代传递来完成树的创建:

class Node:
   def __init__(self, head = None):
     self.head, self.left, self.right = head, None, None
   def __contains__(self, head):
     if head == self.head:
        return True
     return (False if self.left is None else head in self.left) or (False if self.right is None else head in self.right)
   def insert(self, head, vals):
     if self.head is None:
        self.head, self.left, self.right = head, Node(vals[0]), Node(vals[1])
     elif self.head == head:
        self.left, self.right = Node(vals[0]), Node(vals[1])
     else:
        getattr(self, 'left' if self.left and head in self.left else 'right').insert(head, vals)

n = Node()
d = {1:(2,3), 2:(4,5), 4:(6, None), 3:(7,8)}
for a, b in d.items():
   n.insert(a, b)

这会生成正确的树,因为可以很容易地证明可以通过遍历节点实例来获得原始输入:

def to_dict(_n):
  yield (_n.head, (getattr(_n.left, 'head', None), getattr(_n.right, 'head', None)))
  if _n.left:
    yield from to_dict(_n.left)
  if _n.right:
    yield from to_dict(_n.right)

print(dict(to_dict(n)))

输出:

{1: (2, 3), 2: (4, 5), 4: (6, None), 6: (None, None), None: (None, None), 5: (None, None), 3: (7, 8), 7: (None, None), 8: (None, None)}