Python 3.x 在Python中创建一个空的二叉树
我是一名编程新手,在其他问题上找不到答案。 我想创建一个高度为h的空二叉树 我的代码:Python 3.x 在Python中创建一个空的二叉树,python-3.x,binary-tree,Python 3.x,Binary Tree,我是一名编程新手,在其他问题上找不到答案。 我想创建一个高度为h的空二叉树 我的代码: class node: def __init__(self, a = None): self.value = a self.left = None self.right = None def postorder(tree,abba): if tree != None: postorder(tree.left,abba)
class node:
def __init__(self, a = None):
self.value = a
self.left = None
self.right = None
def postorder(tree,abba):
if tree != None:
postorder(tree.left,abba)
postorder(tree.right,abba)
abba.append(tree.value)
def inorder(tree,abba):
if tree != None:
inorder(tree.left,abba)
abba.append(tree.value)
inorder(tree.right,abba)
我想定义一个函数
def getBinaryTree(h):
这给了我一棵h级的树。因此:
有什么想法吗?更新了 要创建高度为
h
的二叉树,需要添加2^(h+1)-1
节点。高度为0的树表示树只包含一个节点,即根节点。例如,要创建高度为3的树,需要添加2^(3+1)-1=15个节点
如果您想创建一组节点,这些节点可以使用给定的代码形成二叉树,您可以这样做
import math
class node:
def __init__(self, a = None):
self.value = a
self.left = None
self.right = None
def getBinaryTree(tree_height):
tree_nodes = [None] * int((math.pow(2, tree_height+1) - 1))
for i in range(tree_height):
start_index = int(math.pow(2, i) - 1)
end_index = int(math.pow(2, i+1) - 1)
for j in range(start_index, end_index):
tree_nodes[j] = node(j)
if j == 0: continue
if j % 2 == 0: # a right child
parent_index = int((j - 2) / 2)
tree_nodes[parent_index].right = tree_nodes[j]
else: # a left child
parent_index = int((j - 1) / 2)
tree_nodes[parent_index].left = tree_nodes[j]
return tree_nodes[0] # returns the root node
def printTree(tree_node, inorder_tree_walk):
if tree_node != None:
printTree(tree_node.left, print_tree)
inorder_tree_walk.append(tree_node.value)
printTree(tree_node.right, print_tree)
root = getBinaryTree(4)
inorder_tree_walk = []
printTree(root, inorder_tree_walk)
print(inorder_tree_walk)
那么,这个程序是做什么的呢
程序创建2^(h+1)-1
节点,以形成高度h
的树。节点存储在列表树\u节点中
。节点之间的父子关系存储在树\u节点中,如下所示
- 元素的左子元素
i
:(2i+1)第个元素
- 元素的右子元素
i
:(2i+2)第个元素
创建子节点时,将其设置为其父节点的左/右子节点。您可以为二叉树定义一个类。然后继续向树中添加节点,直到树的高度为h
@WasiAhmad我该怎么做?是的,我以前见过这段代码。但我不知道如何操纵它来创建一个特定的空树height@Whizkid95空树是指节点没有值的树,对吗?为此,可以在节点中放置一个虚拟值。在那里,您可以计算创建高度h
的树所需的节点数。因此,您可以不断添加这么多节点,以生成高度为h
的二叉树。我明白了这个想法,但我不知道如何在代码中实现它?