从文本文件创建二进制(族)树

时间:2015-04-17 13:21:07

标签: python python-3.x binary-tree

我必须为家庭二进制树编写一些方法,但我仍然坚持初始化树本身,有人可以帮助我/指向一些帮助吗?

class FamilyTree:

    class Node:
        def __init__(self, data, left=None, right=None):
            self.data = data
            self.left = left
            self.right = right
    class Queue:
        def __init__(self):
            self.pole = []
        def enqueue(self, data):
            self.pole.append(data)
        def dequeue(self):
            if self.is_empty():
                return None
            return self.pole.pop(0)
        def is_empty(self):
            return self.pole==[]
    def __init__(self, file_name):
        ...

文件看起来像这样(结构:父子):

  

Pre-Vla
Mir-Bol
Pre-Kaz
  Bra-Ras
Dra-Lub
Lud-Moj
  Sva-Mir
Sta-Pre
Jar-Sta
  Kaz-Pra
Sva-Jar
Vla-Boh
  Jar-Lud
Boh-Lad
Vla-Sve
  Boh-Vla
Mir-Boh
Bol-Dra
  BOL-文胸

我不知何故需要在一些适当的结构(dict,touple?)中解析它,然后从中创建一个树。它是一棵二叉树,所以父母一方最多有2个孩子。

2 个答案:

答案 0 :(得分:0)

这是一种从文件中创建(不一定是二进制)树的方法。树实际上存储在一个字典中,父亲作为键,子列表作为值。

from collections import defaultdict

nodes = []
with open('tree.txt') as f:
    content = f.readlines()
    for line in content:
        for node in line.split('-'):
            nodes.append(node.rstrip()) 

bTree = defaultdict(list)
for father, children in zip(nodes[0::2], nodes[1::2]):
    print 'Inserting (' + father + ', ' + children + ')'
    bTree[father].append(children)
print(bTree)

根据您需要做的事情,这可能比树类更容易实现。

答案 1 :(得分:0)

这会从您的文件中创建二叉树。 它引发了您提供的文件示例的异常,因为有些子节点有两个父节点,所以它不是有效的树。

(我将你的文件命名为#34; parent_child.txt"并将其保存在代码保存的位置。)

class Node(object):
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def __str__(self):
        return self.str_tree()

    def str_tree(self, level=0):
        tree = "{space}{data}\n".format(space="  " * level, data=str(self.data))
        if self.left is not None:
            tree += self.left.str_tree(level + 1)
        if self.right is not None:
            tree += self.right.str_tree(level + 1)
        return tree

    def add_child(self, child):
        if self.left is None:
            self.left = child
        elif self.right is None:
            self.right = child
        else:
            raise Exception("Node {} already has two children".format(self.data))

class FamilyTree(object):
    def __init__(self, file_name):
        self.root = self.generate_tree_from_file(file_name)

    def __str__(self):
        return str(self.root)

    @staticmethod
    def generate_tree_from_file(file_name):
        data_to_node = {}
        has_parent = set()
        with open(file_name) as file_handle:
            for line in file_handle:
                line = line.rstrip('\n')
                parent, child = line.split("-")
                child_node = get_or_create(data_to_node, child)
                parent_node = get_or_create(data_to_node, parent)
                if child in has_parent:
                    raise Exception("Multiple parents for child {}".format(child))
                has_parent.add(child)
                parent_node.add_child(child_node)

        no_parent = data_to_node.viewkeys() - has_parent
        if len(no_parent) > 1:
            raise Exception("The tree has more than one root: {}".format(", ".join(no_parent)))
        return data_to_node[no_parent.pop()]

def get_or_create(data_to_node, data):
    if data in data_to_node:
        return data_to_node[data]
    data_to_node[data] = Node(data)
    return data_to_node[data]

if "__main__" == __name__:
    print(FamilyTree("parent_child.txt"))

适用于此文件,其中每个孩子都有一个父母:

Pre-Vla
Mir-Bol
Pre-Kaz
Bra-Ras
Dra-Lub
Lud-Moj
Sva-Mir
Sta-Pre
Jar-Sta
Kaz-Pra
Sva-Jar
Vla-Boh
Jar-Lud
Boh-Lad
Vla-Sve
Boh-Vla2
Mir-Boh2
Bol-Dra
Bol-Bra