给出二叉树的中序遍历序列和后序遍历序列,编程还原该二叉树。
输入:
第1行为二叉树的中序遍历序列
第2行为二叉树的后序遍历序列
输出:
二叉树的按层遍历序列
- #include
- using namespace std;
-
- struct Node
- {
- char data;
- Node* left;
- Node* right;
- };
-
- // 创建新节点
- Node* NewNode(char data)
- {
- Node* node = new Node;
- node->data = data;
- node->left = NULL;
- node->right = NULL;
- return node;
- }
-
- // 找到在中序遍历序列中的索引位置
- int Search(string in, int start, int end, char value)
- {
- int i;
- for (i = start; i <= end; i++)
- {
- if (in[i] == value) {
- return i;
- }
- }
- return i;
- }
-
- // 使用中序和后序遍历序列构建二叉树
- Node* BuildTree(string in, string post, int inStart, int inEnd)
- {
- static int postIndex = inEnd;
- if (inStart > inEnd) {
- return NULL;
- }
- // 创建新的节点,postIndex位置是根节点
- Node* node = NewNode(post[postIndex--]);
- if (inStart == inEnd) {
- return node;
- }
- // 在中序数组中找到此节点的索引
- int inIndex = Search(in, inStart, inEnd, node->data);
- // 递归构建左右子树
- node->right = BuildTree(in, post, inIndex + 1, inEnd);
- node->left = BuildTree(in, post, inStart, inIndex - 1);
- return node;
- }
-
- // 打印层次遍历序列
- void PrintLevelOrder(Node* root)
- {
- if (root == NULL) return;
- queue
q; - q.push(root);
- while (!q.empty())
- {
- int nodeCount = q.size();
- while (nodeCount > 0)
- {
- Node* node = q.front();
- cout << node->data;
- q.pop();
- if (node->left != NULL)
- q.push(node->left);
- if (node->right != NULL)
- q.push(node->right);
- nodeCount--;
- }
- }
- cout << endl;
- }
-
- // 主函数
- int main()
- {
- string in;
- string post;
- cin >> in >> post;
- int len = in.size();
- Node* root = BuildTree(in, post, 0, len - 1);
- PrintLevelOrder(root);
- return 0;
- }