1
我想做一个函数,使用我的ListBinaryTree:类来构造和打印二叉树,基于作为输入提示的inorder和preorder遍历(以字符串形式,例如。 Inorder = 213,Preorder = 123)。我二叉树类如下:Python:二叉树类:用遍历重建
class ListBinaryTree:
"""A binary tree class with nodes as lists."""
DATA = 0 # just some constants for readability
LEFT = 1
RIGHT = 2
def __init__(self, root_value, left=None, right=None):
"""Create a binary tree with a given root value
left, right the left, right subtrees
"""
self.node = [root_value, left, right]
def create_tree(self, a_list):
return ListBinaryTree(a_list[0], a_list[1], a_list[2])
def insert_value_left(self, value):
"""Inserts value to the left of this node.
Pushes any existing left subtree down as the left child of the new node.
"""
self.node[self.LEFT] = ListBinaryTree(value, self.node[self.LEFT], None)
def insert_value_right(self, value):
"""Inserts value to the right of this node.
Pushes any existing left subtree down as the left child of the new node.
"""
self.node[self.RIGHT] = ListBinaryTree(value, None, self.node[self.RIGHT])
def insert_tree_left(self, tree):
"""Inserts new left subtree of current node"""
self.node[self.LEFT] = tree
def insert_tree_right(self, tree):
"""Inserts new left subtree of current node"""
self.node[self.RIGHT] = tree
def set_value(self, new_value):
"""Sets the value of the node."""
self.node[self.DATA] = new_value
def get_value(self):
"""Gets the value of the node."""
return self.node[self.DATA]
def get_left_subtree(self):
"""Gets the left subtree of the node."""
return self.node[self.LEFT]
def get_right_subtree(self):
"""Gets the right subtree of the node."""
return self.node[self.RIGHT]
def __str__(self):
return '['+str(self.node[self.DATA])+', '+str(self.node[self.LEFT])+', '+\
str(self.node[self.RIGHT])+']'
到目前为止,我有以下几点:
def reconstruct():
inorder = input("Please enter the inorder sequence:")
preorder = input("Please enter the preorder sequence:")
#root = preorder[0]
#left_bottom = inorder[0]
#right_bottom = inorder[len(inorder)-1]
my_tree = ListBinaryTree(int(preorder[0]))
my_tree.insert_tree_left(int(inorder[0]))
my_tree.insert_tree_right(int(inorder[len(inorder)-1]))
print (my_tree)
但它仅适用于与1级或2级树: 输出的一个例子是:
调用函数
reconstruct()
提示:
Please enter the inorder sequence:213
Please enter the preorder sequence:123
打印结果:
[1, 2, 3]
如何更改我的功能,使其可以构建一个树/遍历理论上无限量更高的水平?
重新构建()仅仅是一个单独的功能上ListBinaryTree类调用。这个对我有用。你只需要调用函数:reconstruct()并提示遍历。我不明白你将如何实现递归。它让我感到困惑 – Newbie
有没有你遇到过的递归的一个方面,或者是递归概念的一个普遍问题?如果这是一个普遍问题,那么我建议你查找一个关于递归的教程,或者找一个理解的朋友;通过文本解释整个想法超出了StackOverflow的范围。如果这只是一个特定的问题,那么请问一个后续问题,因为这对于作业至关重要。 – Prune
您使用的是什么版本的Python?这可能是不同之处。 – Prune