python转换排序双链表到BST

时间:2016-03-05 22:13:44

标签: python binary-search-tree doubly-linked-list

这个想法与其他大多数人非常相似,按顺序进行遍历处理,将其视为prevNode,将其作为nextNode 由于某种原因它只是无法工作..似乎没有运行递归?

我通过打印preNode和nextNode

测试了我的DoubleLinked列表是否正确构建

但仍然说'NoneType'对象没有属性'val' 问题出在buildTree

任何一个PLZ帮助

class LinkNode(object):
    def __init__(self, val):
        self.val = val
        self.nextNode = None
        self.prevNode = None


def buildLinkList(arr):
    dummy = head = LinkNode(None)
    dummy.nextNode = head
    for val in arr:
        new_node = LinkNode(val)
        new_node.prevNode = head
        head.nextNode = new_node
        head = head.nextNode
    return dummy.nextNode

def printLink(head):
    while head:
        print head.val
        if not head.nextNode: 
            #print head.val
            return head
        head = head.nextNode

def buildTree(head, n):
    if n <= 0:
        return None
    left = buildTree(head, n / 2)
    print head.val
    root = head
    root.prevNode = left
    head = head.nextNode
    root.nextNode = buildTree(head, n - n / 2 - 1)
    return root


def inorder(root):
    if root:
        inorder(root.prevNode)
        print root.val
        inorder(root.nextNode) 

arr = [1, 2, 3, 4, 5, 6, 7]
head = buildLinkList(arr)
#print head.val
root = buildTree(head, 7)

2 个答案:

答案 0 :(得分:0)

试试这个:

def recursiveMakeDLL(node, prevNode=None):
    if node is None:
        return None

    left = recursiveMakeDLL(node.left, prevNode)
    node.left = left if left is not None else prevNode
    if left is not None:
        left.right = node
    elif prevNode is not None:
        prevNode.right = node

    prevToReturn = recursiveMakeDLL(node.right, node)
    return prevToReturn if prevToReturn is not None else node


def makeDLL(root):
    root = recursiveMakeDLL(root)
    head = root
    tail = root
    while head.left is not None:
        head = head.left
    while tail.right is not None:
        tail = tail.right
    head.left = tail
    tail.right = head

    return head

我们的想法是将prevNode作为递归的一部分传递,这样当堆栈从有序遍历中弹回时,我们可以将当前的左侧设置为不存在。

答案 1 :(得分:0)

head不会在每次递归调用中更新,因此,这里的head应该是全局变量(例如在C中如何使用双指针)。

像这样更新您的buildTree函数

def buildTree(n):
    global head
    if n<=0 :
        return None
    left = buildTree(n/2)
    root = head
    root.prevNode = left
    head = head.nextNode
    root.nextNode = buildTree(n-n/2-1)
    return root