插入二叉树(非BST)Python

时间:2017-07-06 20:42:00

标签: python insert binary-tree binary-search-tree depth-first-search

我试图在我的二叉树中插入一个节点。但是,我不知道正确的方法。我知道我应该运行bfs并插入第一个空位置。如何将其转换为代码?

我正在尝试使用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

但这给了我一个无法访问的代码。 这样做的正确方法是什么?我很沮丧被称为二元树的人,他们真正的意思是BST。

2 个答案:

答案 0 :(得分:2)

是的,如果你想让它平衡并且不关心值插入的顺序应该是广度优先的,那么你是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)

答案 1 :(得分:1)

好的!所以我希望这是你正在寻找的,但你的代码非常好,它只需要一些改变:

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的)。它可以继续发挥作用!

相关问题