先序+中序=树
1. 原文
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:
1 | 7 |
Sample output:
1 | 3 |
2. 解析
先序 根 左 右
中序 左 根 右
后序 左 右 根
故根据先序的根在中序中固定左子树的位置
左子树=1 便得到结果
左子树>1 查找左子树
左子树=0 左子树不存在,查找右子树
右子树=1 得到结果
右子树>1 查找右子树
3. AC代码
1 |
|