【问题标题】:Binary Tree and Linked List:二叉树和链表:
【发布时间】:2013-03-15 09:11:07
【问题描述】:

假设我有节点类:

class Node:

    def __init__(self, data, link=None):
        self.data = data
        self.link = link

class BTNode:

    def __init__(self, item, left=None, right=None):
        self.item = item
        self.left = left
        self.right = right

我想创建一个二叉搜索树中序遍历的链表。

到目前为止我所拥有的是:

def inorder(root):

    root = _inorder(root)[0] # return head of linked list

# helper function that returns the head and tail of the linked list. 
def _inorder(root):

    if root is None:
        return None, None

    else:
        temp = Node(root.item)
        if root.left:
            left_head, left_tail = _inorder(root.left)
            left_tail.link = temp
        if root.right:
            right_head, right_tail = _inorder(root.right)
            temp.link = right_head

        return left_head, right_tail

测试:

if __name__ == '__main__':
    a1 = BTNode('A')
    a2 = BTNode('B')
    a3 = BTNode('C')
    a4 = BTNode('D')
    a5 = BTNode('G')
    a6 = BTNode('E')
    a7 = BTNode('F')
    a1.left = a2
    a1.right = a3
    a2.right = a4
    a4.left = a5
    a3.left = a6
    a3.right = a7
    x = inorder(a1)

但是我得到了错误:

UnboundLocalError:赋值前引用了局部变量“left_head”

如果我这样做:

def _inorder(root):

    if root is None:
        return None, None

    else:
        temp = Node(root.item)
        #if root.left:
        left_head, left_tail = _inorder(root.left)
        left_tail.link = temp
        #if root.right:
        right_head, right_tail = _inorder(root.right)
        temp.link = right_head

        return left_head, right_tail

那么错误就变成了:NoneType' object has no attribute 'link' 任何人都可以看到问题,因为我认为我的逻辑是正确的。

【问题讨论】:

    标签: python binary-search-tree


    【解决方案1】:

    第一种情况:

        if root.left:
            left_head, left_tail = _inorder(root.left)
            left_tail.link = temp
        if root.right:
            right_head, right_tail = _inorder(root.right)
            temp.link = right_head
    
        return left_head, right_tail
    

    如果您不输入任何一个 if,您将永远不会分配 left_head 或 right_tail。

    第二个错误是因为你的第一次检查:

    if root is None:
        return None, None
    

    给了这个任务:

        left_head, left_tail = _inorder(root.left)
    

    将使left_head 和left_tail 都为None。这会导致您在下一行看到的爆炸。

    【讨论】:

    • 好吧,要么检查没有子节点的 _inorder 调用的返回值,要么在调用 _inorder(node.left) 之前检查 node.left != None。右边也一样。我建议您自己尝试一下并找出答案。
    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 2015-09-24
    • 1970-01-01
    • 2017-09-16
    • 2017-08-23
    • 2017-12-12
    相关资源
    最近更新 更多