使用二进制元素构建二叉树算法

时间:2018-06-02 13:34:13

标签: python binary-tree

我想在python中基于txt文件构建二叉树算法,该文件包含随机生成的反映ip地址表的二进制元素,但是当我运行我的代码时会出现错误信息:

"D:\Nouveau dossier\projectpy\venv\Scripts\python.exe" C:/Users/balala/.PyCharmCE2018.1/config/scratches/ARB/Binary.py
Traceback (most recent call last):
  File "C:/Users/balala/.PyCharmCE2018.1/config/scratches/ARB/Binary.py", line 66, in <module>
    ab.constructTree(sr)
  File "C:/Users/balala/.PyCharmCE2018.1/config/scratches/ARB/Binary.py", line 35, in constructTree
    self.RC.RC.constructTree(k)
AttributeError: 'NoneType' object has no attribute 'constructTree'

使用退出代码1完成处理

我的代码来源:

import os
from random import randrange


class BinTree:
    def __init__(self,val=" "):
        self.RC=None    #le fils droit
        self.LC=None   # le fils gauche
        self.key=val    # la cle

    def getRC(self):
            return self.RC
    def getLC(self):  # retourner le noeud gauche
        return self.LC
    """
    """
    def setkey(self,Val):
        self.key=Val
        """
        """
    def getkey(self):
        return self.key


    def constructTree(self, k=" "):
        if self is None:
            self=BinTree(k)
        elif k == "0":
             if self.LC is None:
                 self.LC=BinTree(k)
             self.LC.LC.constructTree(k)
        elif k=="1":
            if self.RC is None:
               self.RC = BinTree(k)
            self.RC.RC.constructTree(k)

    def printTree(self):
      if self:
          print(self.key,end="")
          if self.LC:
            self.LC.printARB()
          if self.RC:
             self.RC.printARB()

"""racine=BinArb(2)
racine.inserkey(3)
racine.inserkey(1)
racine.inserkey(4)
racine.inserkey(0)
racine.printARB()"""
ab=BinTree(0)
file1=open("bin1.txt", "w")
for i in range(0,6):
 for i in range(0,randrange(1,7)):
    l=str(randrange(0,2))
    s=l+ " "
    file1.writelines(s)
 j= " \n"
 file1.writelines(j)
file1.close()
file2=open("bin1.txt","r")
for line in file2:
    lis=line.split()
    for l in range(0,len(lis)):
        sr=str(lis[l])
        ab.constructTree(sr)

file2.close()
ab.printARB()

1 个答案:

答案 0 :(得分:0)

第35行出现错字:

self.RC.RC.constructTree(k)

这可能应该是:

self.RC.constructTree(k)