使用自定义数据类型的Python3元组

时间:2018-05-27 15:41:44

标签: python python-3.x algorithm tuples

此代码旨在对树执行级别顺序遍历。我试图将级别信息和节点元素存储在队列中。但是当我尝试从队列中提取级别元素时,代码会出错。

有人可以解释为什么这个代码在尝试访问元组的第二个元素时会出错吗?这个元组的用途是不正确的吗?

from collections import defaultdict
from queue import Queue

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

    def levelOrderTraversal(root):
        result = defaultdict(list)
        if not root:
            return result
        q = Queue()
        level = 0
        q.put((level, root))

        while not q.empty():
            e = q.get()
            level = e[0]
            #Above line throws error: TypeError: 'int' object is not subscriptable
            node = e[1]
            result[level].append(node.val)
            if node.left:
                q.put(level + 1, node.left)
            if node.right:
                q.put(level + 1, node.right)
        return result

    def test1():
        root = Node(1)
        root.left = Node(2)
        root.right = Node(3)        

        levelOrderTraversal(root)

    test1()

1 个答案:

答案 0 :(得分:1)

你在提供队列时搞砸了。最初你正在做q.put((root,level))和其他一些你正在做的地方q.put(level + 1,node.left),q.put(level + 1,node.right)。请参阅以下更正的代码:

from collections import defaultdict
from queue import Queue

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

def levelOrderTraversal(root):
    result = defaultdict(list)
    if not root:
        return result
    q = Queue()
    level = 0
    q.put((level, root))

    while not q.empty():
        e = q.get()
        level = e[0]
            #Throws error: TypeError: 'Node' object does not support indexing
        node = e[1]
        result[level].append(node.val)
        if node.left:
            q.put((level + 1,node.left))
        if node.right:
            q.put((level + 1,node.right))
    return result

def test1():
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    return levelOrderTraversal(root)

print(test1()) # prints defaultdict(<class 'list'>, {0: [1], 1: [2, 3]})

Ideone https://ideone.com/Xy0OR8

中的工作代码