簡體   English   中英

在二叉樹(非BST)Python中插入

[英]Insertion in Binary Tree (Not BST) Python

我正在嘗試在我的二叉樹中插入一個節點。 但是,我不知道執行此操作的正確方法。 我知道我應該運行bfs並插入第一個null位置。 如何將其轉換為代碼?

我嘗試使用DFS:樹看起來像這樣:

class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
def insert(node, val):
     if not node:
           return Node(val)
     if not node.left:
           node.left = Node(val)
           return 
     if not node.right:
           node.right = Node(val)
           return 
     return insert(node.left, val)
     return insert(node.right, val)

n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8

但這給了我無法訪問的代碼。 正確的方法是什么? 人們對Binary Tree真正的意思是BST感到非常沮喪。

是的,如果您希望平衡它並且不關心值插入的順序應該廣度優先,那么您100%正確,因此我為您修改了一些代碼,但我最初所說的仍然有效:

要進行bfs遍歷,您必須使用另一個數據結構,即隊列。 隊列是FIFO,這意味着您最終要在訪問下一個級別之前訪問每個級別的每個節點。 有趣的是,使此深度首先從末尾彈出,而不是從開頭開始模擬堆棧。

def insert(node, val):
    """
    Always returns the root of the tree
    """
    if not node:
        return Node(val)
    queue = [node]
    while len(queue) > 0:
        # n is the current node in the tree
        n = queue.pop(0)

        # if it has no children insert node
        # start from the left
        if not n.left:
            n.left = Node(val)
            return node
        if not n.right:
            n.right = Node(val)
            return node

        queue.append(n.left)
        queue.append(n.right)

好的! 因此,我希望這是您要尋找的東西,但是您的代碼非常好,只需要進行一些更改即可:

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

    def __str__(self): #This allows you to print out the nodes for testing, other "magic" methods can be created here too!
        return str(self.val)

def insert(node, val=None):
     if not val:
        return Node(node) #This will create a new node if val is None
     if not node.left:
           node.left = val
           return 
     if not node.right:
           node.right = val
           return 
     return insert(node.left, val)
     return insert(node.right, val)


def main():
     n1 = insert(1)
     n2 = insert(2)
     n3 = insert(3)
     n4 = insert(4)
     n5 = insert(5)
     n6 = insert(6)
     n7 = insert(7)
     n8 = insert(8)

     insert(n1, n2)
     insert(n1, n3)
     insert(n2, n4)
     insert(n2, n5)
     insert(n3, n6)
     insert(n3, n7)
     insert(n4, n8)

     print(n1.left)
     print(n3.left)

main()

這對我的測試有效! 為了使函數創建新的節點,我更改了insert()背后的邏輯(盡管我知道這不一定是您想要的方式,您可以將其改回來!)。 盡管有很多其他方法可以實現此功能,但是我認為這是最接近原始代碼的方法。

希望能幫助到你!

PS另一個很棒的資源是Interactive Python (授予本章的內容是有關BST的)。 將來仍然有用!

暫無
暫無

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

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