Description
二哥学了二叉树的顺序存储后,被下面一个问题难住了,于是他请你帮他解决。给你一个前序遍历和中序遍历,问顺序存储的数组是什么样子的。
Example
Input Format
第一行为前序遍历,第二行为中序遍历,节点个数不超过26.
Output Format
输出一行,表示顺序存储的数组,以空格隔开,NULL表示空节点,数组空间不超过1000个节点.
Sample Input
ABCD
BADC
Sample Output
A B C NULL NULL D
C++实现如下:
#include <iostream>
#include <string>
using namespace std;
struct node
{
char val;
node *left;
node* right;
node() :val(0), left(nullptr), right(nullptr) {}
node(char v)
:val(v), left(nullptr), right(nullptr) {}
};
node* init(string s1, string s2)
{
node *cur_root = new node(s1[0]);
int num = 0;
for (; num < s2.length(); num++)
if (s1[0] == s2[num]) break;
if (num > 0)
cur_root->left = init(s1.substr(1, num), s2.substr(0, num));
if (num < s2.length() - 1)
cur_root->right = init(s1.substr(num + 1, s1.length() - num - 1), s2.substr(num + 1, s2.length() - num - 1));
return cur_root;
}
void SaveTree(node *root, int *arr, int pos)
{
arr[pos] = root->val - 'A' + 1;
if (root->left != nullptr)
SaveTree(root->left, arr, pos * 2);
if (root->right != nullptr)
SaveTree(root->right, arr, pos * 2 + 1);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string s1, s2;
cin >> s1 >> s2;
node *root = init(s1, s2);
int arr[1005];
for (int i = 0; i < 1005; i++) arr[i] = 0;
SaveTree(root, arr, 1);
int tail = 1004;
for (; tail >= 0; tail--)
if (arr[tail]) break;
for (int i = 1; i <= tail; i++)
{
if (arr[i])
cout << char(arr[i] - 1 + 'A') << " ";
else
cout << "NULL ";
}
cout << endl;
return 0;
}