我试图在我的二叉树中插入一个节点。但是,我不知道这样做的正确方法。我明白我应该运行一个bfs并插入第一个空位置。我如何将它翻译成代码?插入二叉树(非BST)Python
我试图与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。
您可以先在您的问题中修复缩进吗?它有助于了解什么是实际错误,以及在SO上发布代码的工件。 – cosinepenguin
其实在代码中有很多错误......'n.left'和'n.right'在做什么?我不认为你曾经宣布过''''''。 – cosinepenguin
缩进是可以的我想。高清确实是在课外 –