Python:使用Pre和Inorder构建二叉树

时间:2015-10-22 23:46:25

标签: python recursion tree tree-traversal

我需要帮助来完成我的函数的递归部分。该函数应该使用我的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)

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

其输入和输出的一个例子是:

build_tree('3241657', '1234567')

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)

输入

build_tree('3241657', '1234567')

返回

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

有人可以帮我解决递归部分吗?

谢谢

1 个答案:

答案 0 :(得分:1)

你使递归部分比必要的更难。

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)来进一步简化它,因此它只需要出现一次。