簡體   English   中英

從二叉搜索樹創建列表

[英]Creating a List from a Binary Search Tree

我正在嘗試在二進制搜索樹中列出所有項目。 我了解遞歸,但是我不知道如何使它返回每個值,然后將其附加到列表中。 我想創建一個名為makeList()的函數,該函數將返回樹中所有項目的列表。 makeList()函數外,程序中的所有函數均起作用,並包含在內以確保每個人都了解我如何設置樹的基本結構。

class Node(object):
    def __init__(self, data):
        self.data = data
        self.lChild = None
        self.rChild = None

class Tree(object):
    def __init__(self):
        self.root = None

    def __str__(self):
        current = self.root

    def isEmpty(self):
        if self.root == None:
            return True
        else:
            return False

    def insert (self, item):
        newNode = Node (item)
        current = self.root
        parent = self.root

        if self.root == None:
            self.root = newNode
        else:
            while current != None:
                parent = current
                if item < current.data:
                    current = current.lChild
                else:
                    current = current.rChild

            if item < parent.data:
                parent.lChild = newNode
            else:
                parent.rChild = newNode

    def inOrder(self, aNode):
        if aNode == None:
            pass
        if aNode != None:
            self.inOrder(aNode.lChild)
            print aNode.data
            self.inOrder(aNode.rChild)

    def makeList(self, aNode):
        a = []
        self.inOrder(aNode)
        a += [aNode.data]
        print a

n = Tree()
for i in [4,7,2,9,1]:
    n.insert(i)

n.makeList(n.root)

查看我的makeList()函數,我可以看到為什么它不起作用,但是我不知道如何使其起作用。

編輯

好,我知道了! 我什至得到兩個答案:

def makeList(self, aNode, a = []):
    if aNode != None:
        self.makeList(aNode.lChild, a)
        a += [aNode.data]
        self.makeList(aNode.rChild, a)
    return a

def makeList2(self, aNode):
    if aNode is None:
        return []
    return self.makeList2(aNode.lChild) + [aNode.data] + self.makeList2(aNode.rChild)

回首過去,我發現我不太了解遞歸,是時候開始嘗試了! 有人有很好的遞歸資源嗎?

另一個問題,比如說我調用了makeList()函數。 當Python進入makeList() ,當它到達self.makeList(aNode.lChild, a)時,它會再次開始運行該函數,同時仍完成makeList()函數,或者一切都停止了,而只是makeList()開始這是新的aNode嗎?

我希望這是有道理的。

inOrder打印內容,但不返回任何內容,因此它對於構建列表毫無用處。 您需要一種方法來按順序返回每個節點。 這可能是您的課程尚未涵蓋的內容,但請查看yield命令。

你好親密! makeList可以非常簡單:

def makeList(self, aNode):
    if aNode is None:
        # Stop recursing here
        return []
    return self.makeList(aNode.lChild) + [aNode.data] + self.makeList(aNode.rChild)

基本上,請確保您不嘗試遞歸過去的空節點。 然后返回左樹的列表,當前節點和右樹的列表。

基本思想是這樣的:

def makeList(self):
    return self.lChild.makeList() + [self.data] + self.rChild.makeList()

看到它與inOrder本質上是一樣的東西嗎?

您的程序具有不同的結構,這使其難以實現,但是基本思想是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM