简体   繁体   English

在 Python 中将值插入二叉树

[英]Inserting value into Binary Tree in Python

I need to add values to my Binary Tree (Node).我需要向我的二叉树(节点)添加值。

Here is my class:这是我的课:

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

def __str__(self):
    return "{}".format(self.val)


file = open("/home/dzierzen/Downloads/text.txt", "r")

lines = []

for line in file:
    cleaned_line = re.sub(r"\s+", "", line)
    #

I have txt file with something like this.我有这样的txt文件。 L means Left, Right mean Right on the tree. L 在树上表示左,右表示右。 Of course the real txt file contains much more records.当然,真正的 txt 文件包含更多的记录。 My questions is: how to deal with that?我的问题是:如何处理? How to add this values to the tree?如何将此值添加到树中?

G RR
A
C L
F LLR
X LLL
F R
X RL
H LLG RR
C L
F LLR
X LLL
F R
X RL
H LL

I'm building the tree by going through the list and deciding on the L/R characters which way to go.我正在通过浏览列表并决定 L/R 字符走哪条路来构建树。 When I found a non existing leaf, I create a Node there with the value of None.当我发现一个不存在的叶子时,我在那里创建了一个值为 None 的节点。 Multiple visits to the same leaf will overwrite the value, but you can easily change that.多次访问同一叶子会覆盖该值,但您可以轻松更改该值。 If the splitted text has only one value, that will be the root Node's value.如果拆分的文本只有一个值,则该值将是根节点的值。

I added a printing method that will traverse the tree and print the root of the subtree, then the left and right leaves.我添加了一个打印方法,该方法将遍历树并打印子树的根,然后是左右叶。 It also indents it according to it's level.它还根据它的级别缩进它。

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

    def __str__(self):
        return "{}".format(self.val)

    def _printTree(self, node, level=0):
        if node != None:
            print(f"{'-'*level}{node}")
            self._printTree(node.left,level+1)
            self._printTree(node.right,level+1)

    def printTree(self):
        self._printTree(self)

p = s.split('\n')
root = Node(None)
for k in p:
    v = k.split()
    if len(v) == 1:
        root.val = v[0]
    else:
        r = root
        for c in v[1]:
            if c == 'L':
                if r.left is None:
                    r.left = Node(None)
                r = r.left
            elif c == 'R':
                if r.right is None:
                    r.right = Node(None)
                r = r.right
        r.val = v[0]

root.printTree()

Using the input text you wrote this is what gets generated:使用您编写的输入文本生成以下内容:

A
-C
--H
---X
---F
-F
--X
--G

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

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