python中具有不同类型节点的树上的递归

2024-03-28 09:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个由内部节点(由类内部表示)和叶节点(由类节点表示)组成的树类。在

class Node(object):
    def __init__(self,bits,data):
        self.bits = bits
        self.data = data


class Inner(object):
    def __init__(self):
        self.bits = ''
        self.c0  = None
        self.c1 = None


class Tree(object):
    def __init__(self):
        self.root = None

   def insert_Item(self,key,datastr):
   #code goes here

我可以使用insert方法插入叶和内部节点。在

^{pr2}$

这个问题出现在insert方法的递归公式中。我不能调用self.root.c0.insert()self.root.c1.insert()假设自我.root.c0和自我.root.c1指向内部节点。这是因为内部类没有insert函数。在

如何使insert方法以递归的方式在所有三个类上工作?类似地,我不能进行树遍历,因为我得到的错误是内部对象没有属性'data'


Tags: 方法selfnonedata节点objectinitdef
1条回答
网友
1楼 · 发布于 2024-03-28 09:30:55

考虑更改您的实现,这样树只有节点,遍历方法是Node类的类方法,节点的标识是内部的还是叶子的,这取决于节点是否有子节点。在

一般来说,在OOP中,您希望实现尽可能少的类,以完全消除程序功能的歧义,同时也为其他程序员提供必要的增强实用程序。在实现一个新的子类之前,想一想:另一个类可以在不使用多态性的情况下执行这个类的方法吗?在

class Node(object):

      leftNode = None
      rightNode = None
      root = None

      def __init__(self,data,bit):
         self.bits = bit
         self.data = data
    /* I will make an assumption about the structure, left us assume the tree is simple, and preferentially populates the left subtree */
      def insert_Item(self,data,bit):
         if (leftNode == None):
              self.leftNode = Node(data,bit)
         elif (rightNode === None):
              self.rightNode = Node(data,bit)
         else:
              self.leftNode.insert_Item(data, bit)

class Tree(object):
    root = None
    def __init__(self, rootNode):
        self.root = rootNode

    def add_data(self,data,bit):
        self.root.insert_Item(data,bit)

只要稍加修改,这两个类就可以满足您的需要。我建议参考本文作为初级读物:http://interactivepython.org/runestone/static/pythonds/index.html

相关问题 更多 >