Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
题目大意
给定一颗二叉树的前序遍历和中序遍历顺序,要求输出后序遍历的第一个节点
分析
每一个前序遍历的第一个节点都是这部分二叉树的根,在中序遍历中找到这个节点的位置,左边是左子树,右边是右子树。存在左子树的情况下,接下来去遍历左子树,按照前面的方法找到左子树的左右子树。如果没有左子树则去遍历右子树。
这样的方法可以用递归去写,也可以不用递归写。
但是倒数第二个测试点都会有问题。递归的话会内存超限,不递归会超时,o(︶︿︶)o
最后一个测试点也有问题,使用列表推导式转换前序和后续会非零返回,要套一层异常捕捉就好了,这是为什么???
Python实现
def dfs(pre,inorder):
global flag
if not flag:
if len(pre) == 1:
print(pre[0])
flag = True
root = pre[0]
index = inorder.index(root)
if index >0:
inorder_first = inorder[:index]
pre_first = pre[1:1+index]
dfs(pre_first,inorder_first)
else:
inorder_second = inorder[index+1:]
pre_second = pre[1+index:]
dfs(pre_second,inorder_second)
else:
return
def main():
input()
line = input().split(" ")
pre=[]
for x in line:
try:
pre.append(int(x))
except:
break
line = input().split(" ")
inorder=[]
for x in line:
try:
inorder.append(int(x))
except:
break
dfs(pre,inorder)
if __name__ == "__main__":
flag = False
main()