Python: 使用前序和中序构建二叉树

2024-04-19 21:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助完成我函数的递归部分。这个函数应该使用我的ListBinaryTree类来帮助重建一个树,因为它的序和前序遍历是字符串格式的:例如

preorder = '1234567'
inorder = '3241657' 

def build_tree(inorder, preorder):
    head = preorder[0]
    print(head)
    head_pos = inorder.index(head)
    print(head_pos)
    left_in = inorder[:head_pos]
    print(left_in)
    right_in = inorder[(head_pos+1):]
    print(right_in)
    left_pre = preorder[1:-len(right_in)]
    print(left_pre)
    right_pre = preorder[-len(right_in):]
    print(right_pre)

它在前序遍历和序遍历中查找重要值,并将树拆分以确定树的左侧和右侧的数字。在

其输入和输出示例如下:

^{pr2}$

一。在

1
3
324
657
234
567

我用来创建树的类如下:

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])+']'

对于函数的递归部分,我尝试了如下操作:

my_tree= ListBinaryTree(head)
while my_tree.get_value() != None:
        left_tree = build_tree(left_in, left_pre)
        right_tree = build_tree(right_in, right_pre)
        my_tree.insert_value_left(left_tree)
        my_tree.insert_value_right(right_tree)
    print (my_tree)

但它返回一个“索引超出范围”错误。在

同样适用于:

def build_tree(inorder, preorder):
    head = preorder[0]
    head_pos = inorder.index(head)
    left_in = inorder[:head_pos]
    right_in = inorder[(head_pos+1):]
    left_pre = preorder[1:-len(right_in)]
    right_pre = preorder[-len(right_in):]
    if left_in:
        left_tree = build_tree(left_in, left_pre)
    else:
        left_tree = None
    if right_in:
        right_tree = build_tree(right_in, right_pre)
    else:
        right_tree = None
    my_tree =  ListBinaryTree(head, left_tree, right_tree)
    print(my_tree)

输入

^{pr2}$

退货

[3, None, None]
[4, None, None]
[2, None, None]
[6, None, None]
[7, None, None]
[5, None, None]
[1, None, None]    

谁能帮我做递归部分吗?在

谢谢


Tags: oftheinselfrightnonenodetree
1条回答
网友
1楼 · 发布于 2024-04-19 21:13:23

你让递归部分变得比必要的困难得多。在

if left_in:
    left_tree = build_tree(left_in, left_pre)
else:
    left_tree = None

if right_in:
    right_tree = build_tree(right_in, right_pre)
else:
    right_tree = None

return ListBinaryTree(head, left_tree, right_tree)

您也许可以通过将空序列的检查移到函数的顶部(例如if not inorder: return None)来进一步简化它,这样它只需要出现一次。在

相关问题 更多 >