Python:TypeError 无法连接 'str and ' 列表'对象

标签 python binary-tree typeerror

我正在编写一个 python 脚本来创建二叉树,但在使用教授的示例代码打印“分支”时,我不断收到 TypeError:无法连接“str”和“list”对象 ' 基于节点位置的树:

    def print_node(self, depth):
        print('---' * depth + self.key)
        if self.left_child is not None:
            self.left_child.print_node(depth + 1)
        if self.right_child is not None:
            self.right_child.print_node(depth + 1)

但是,我修改了在其他地方找到的二叉树的代码,它仍然不起作用,但它也没有抛出我在使用教授的代码时得到的 TypeError 。因此,我很困惑导致抛出错误的问题是什么。

完整代码:

class BinaryTreeNode():
    def __init__(self, key):
        self.key = key
        self.left_child = None
        self.right_child = None

    def print_node(self, depth):
        print('---' * depth + str(self.key))
        if self.left_child is not None:
            self.left_child.print_node(depth + 1)
        if self.right_child is not None:
            self.right_child.print_node(depth + 1)

    def insert_node(self, newNode):
        if newNode == self.key:
            return False
        elif newNode < self.key:
            if self.left_child:
                return self.left_child.insert_node(newNode)
            else:
                self.left_child = BinaryTreeNode(newNode)
                return True
        else:
            if self.right_child:
                return self.right_child.insert_node(newNode)
            else:
                self.right_child = BinaryTreeNode(newNode)
                return True

class BinaryTree():
    def __init__(self):
        self.root = None

    def insert(self, k):
        if self.root:
            return self.root.insert(k)
        else:
            self.root = BinaryTree(k)
            return True

    def print_tree(self):
        self.root.print_node(k)

if __name__ == '__main__':
    tree = BinaryTree()
    tree.insert(5)
    tree.insert(28)
    tree.insert(17)
    tree.insert(22)
    tree.insert(229)
    tree.insert(222)
    tree.insert(2)
    tree.print_tree()

预期的结果应该是打印如下的二叉树:

5
---2
---28
-----17
-------22
----------21
------229
--------222

编辑

Traceback (most recent call last):
  File "G:/Programming Projects/BinaryTree.py", line 48, in <module>
    tree.print_tree()
  File "G:/Programming Projects/BinaryTree.py", line 37, in print_tree
    self.root.print_node(0)
  File "G:/Programming Projects/BinaryTree.py", line 10, in print_node
    print('---' * depth + self.key)
TypeError: cannot concatenate 'str' and 'list' objects

修改后的“工作”代码:

class Node():

    def __init__(self,val):
        self.value = val
        self.left_child = None
        self.right_child = None

    def print_node(self, depth):
        print('---' * depth + self.value)
        if self.left_child is not None:
            self.left_child.print_node(depth + 1)
        if self.right_child is not None:
            self.right_child.print_node(depth + 1)

    def _insert(self,data):
        if data == self.value:
            return False
        elif data < self.value:
            if self.left_child:
                return self.left_child._insert(data)
            else:
                self.left_child = Node(data)
                return True
        else:
            if self.right_child:
                return self.right_child._insert(data)
            else:
                self.right_child = Node(data)
                return True

    def _inorder(self):
        if self:
            if self.left_child:
                self.left_child._inorder()
            print(self.value)
            if self.right_child:
                self.right_child._inorder()



class Tree():

    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root:
            return self.root._insert(data)
        else:
            self.root = Node(data)
            return True
    def inorder(self):
        if self.root is not None:
            return self.root._inorder()
        else:
            return False

if __name__=="__main__":
    a = Tree()
    a.insert(5)
    a.insert(28)
    a.insert(17)
    a.insert(22)
    a.insert(229)
    a.insert(222)
    a.insert(2)
    a.inorder()

最佳答案

BinaryTree.insert()方法有一个错误:

def insert(self, k):
    if self.root:
        return self.root.insert_node(newNode)
    else:
        self.root = BinaryTreeNode(newNode)
        return True

此代码忽略 k参数并使用全局 newNode反而。该值设置为一个列表:

newNode = []

因此这会创建 key 的节点属性设置为空列表,这打破了 print_node() 的假设功能 self.key始终是一个字符串。

要使代码正常工作,您需要进行两项更改:

  • 修复插入以使用 k而不是newNode :

    def insert(self, k):
        if self.root:
            return self.root.insert_node(k)
        else:
            self.root = BinaryTreeNode(k)
            return True
    
  • 要么转换 self.key连接到 '---' * depth 之前先连接到字符串,或者仅使用树中的字符串值。转换为字符串更灵活:

    print('---' * depth + str(self.key))
    

请注意BinaryTreeNode.insert_node()方法也不完整;没有代码处理插入到子树中;只有newNode == self.keynewNode < self.key案件处理完毕后,newNode > self.key case 被省略,大概 True如果添加新节点,则应返回:

def insert_node(self, newNode):
    if newNode == self.key:
        return False
    elif newNode < self.key:
        if self.left_child:
            return self.left_child.insert_node(newNode)
        else:
            self.left_child = BinaryTreeNode(newNode)
            return True
    else:
        if self.right_child:
            return self.right_child.insert_node(newNode)
        else:
            self.right_child = BinaryTreeNode(newNode)
            return True

应用这 3 个修复后,代码最终输出预期的缩进显示。

关于Python:TypeError 无法连接 'str and ' 列表'对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46746996/

相关文章:

python - pyqt在滚动区域展开网格

algorithm - 树哈希 : How to verify if a range is tree-hash-aligned?

python - 如何克服 TypeError : unhashable type: 'list'

python - 类型错误: ('Keyword argument not understood:' , 'inputs' )

python - 有没有更好的方法在 python 中编写嵌套 if 语句?

python - 维护 Pandas 多索引数据帧的顺序

python - 使用 SQLAlchemy Integer 字段创建用于过滤的 timedelta 对象

java - 需要在Java中通过数组来呈现二叉搜索树的节点。我怎么做?

algorithm - 我试图在时间 O(1) 的二叉搜索树中找到一个键的后继

python - NLTK 停用词返回错误 "LazyCorpusLoader is not callable"