题目描述
给定一个二叉树的前序遍历和中序遍历的序列,输出对应这个二叉树的后续遍历序列。
输入描述:
输入为一行。 两个字符串,分别表示二叉树的前序遍历和中序遍历结果,用空格分隔。保证数据合法
输出描述:
对应输出后序遍历序列
示例1
输入
ABDEC DBEAC
输出
DEBCA
采取的是先重建二叉树,然后后序遍历的方法
# -*- coding:utf-8 -*-
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
else:
node = TreeNode(pre[0])
index = tin.index(node.val)
node.left = self.reConstructBinaryTree(pre[1:index+1], tin[:index])
node.right = self.reConstructBinaryTree(pre[index+1:], tin[index+1:])
return node
def read(self, node):
if not node:
return []
else:
return self.read(node.left)+self.read(node.right)+[node.val]
ss = Solution()
line = sys.stdin.readline().strip()
arr = line.split(' ')
pre = list(arr[0])
tin = list(arr[1])
resultput = ss.read(ss.reConstructBinaryTree(pre, tin))
print(''.join(i for i in resultput))