一、题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树
二、代码实现
1.思路
(1)首先可知前序遍历的顺序是根(跟节点)-左子树-右子树的顺序,那么列表中的第一个数即为根结点;
(2)中序遍历的顺序是左-根-右的顺序,即可根据前序遍历的列表中根结点(第一个元素)的位置在中序遍历的列表中的位置来确定左右子树;可以通过递归的思路来重建二叉树
2.代码
#-*- coding:utf-8 -*- ''' binary_tree用来定义一个二叉树的类,return_head是根据初始列表的第一位来确定根结点 并通过forword_sort函数递归添加左右节点 ''' class binary_tree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def forword_sort(root, forword, middle, pos): sub_tree = binary_tree(forword[0]) if pos == 0: root.left = sub_tree if pos == 1: root.right = sub_tree index = middle.index(forword[0]) if index != 0: forword_sort(sub_tree,forword[1:index+1], middle[:index], 0) if index != len(middle)-1: forword_sort(sub_tree, forword[index+1:], middle[index+1:], 1) def return_head(forword, middle): root = binary_tree(forword[0]) index = middle.index(forword[0]) if index != 0: forword_sort(root, forword[1:index+1], middle[:index], 0) if index != len(middle)-1: forword_sort(root, forword[index+1:], middle[index+1:], 1) return root def search_tree(head): if head is not None: print(head.value) search_tree(head.left) search_tree(head.right) ''' 根据下面前序遍历和中序遍历的列表来重构二叉树,并在最后用前序遍历的方式打印出树的所有节点 ''' if __name__=='__main__': forword_sort_lst=[1, 2, 4, 7, 3, 5, 6, 8] middle_sort_lst=[4,7,2,1,5,3,8,6] head = return_head(forword_sort_lst, middle_sort_lst) search_tree(head)