【问题标题】:recursion on a tree with different type of nodes in python在python中具有不同类型节点的树上的递归
【发布时间】:2016-03-28 22:34:02
【问题描述】:

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

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

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

t = Tree()
t.insert('1111', 'A')
t.insert('1110', 'B')

问题出现在插入方法的递归公式中。假设 self.root.c0 和 self.root.c1 指向内部节点,我无法调用 self.root.c0.insert()self.root.c1.insert()。这是因为Inner类没有插入功能。

如何使插入方法以递归方式在所有三个类上工作?同样,我无法进行树遍历,因为我得到内部对象没有属性“数据”的错误

【问题讨论】:

  • 为什么不做一个父类,让它们都继承自并实现insert方法呢?
  • 叶子只是一个没有子节点的节点。为什么需要一个完全独立的类来识别它?
  • @solarc 方便你放一个类的骨架吗
  • @cricket_007。这是因为这个疯狂的规范stackoverflow.com/questions/36166004/…
  • 哦,我明白了。是的,我完全不会错过复杂的二叉树问题。

标签: python recursion data-structures binary-tree


【解决方案1】:

考虑改变你的实现,所以树只有节点,遍历方法是 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

【讨论】:

  • 你能举个例子来解释你上面的答案吗
  • 我已经举了一个例子并更正了格式。
猜你喜欢
  • 2010-12-09
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多