题目描述
深度遍历一棵二叉树有先序,中序和后序三种方式,并且根据遍历序列能确定一棵二叉树,要唯一确定一棵二叉树至少需要两种遍历序列 先序+中序 或 后序+中序,(先序+后序无法唯一确定) 现在给定你一棵二叉树的先序和中序序列,请你构造出这棵二叉树,并且输出其层序遍历结果
输入
输入包含多组测试数据
对每组测试数据:
第一行为一个正整数n(0<n<=100)代表二叉树节点个数
第二行为这棵树的先序遍历序列
第三行为其中序遍历序列
(每个节点为整型数字)
当读到文件结尾时输入结束.
输出
对每组测试数据
在一行中输出这棵树的层序遍历结果 中间用空格隔开,最后一个数字后面不得有空格。
样例输入
8
7 10 4 3 1 2 8 11
4 10 3 1 7 11 8 2
样例输出
7 10 2 4 3 8 1 11
:
#include <iostream> #include <queue> using namespace std; typedef struct Node { int data; struct Node* LChild; struct Node* RChild; }Node; //种树 Node* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder) { int rootValue = startPreorder[0]; Node* root = new Node; root->data = rootValue; root->LChild = root->RChild = NULL; if (startPreorder == endPreorder) { if (startInorder == endInorder && *startPreorder == *endInorder) return root; } int* rootInorder = startInorder; while (rootInorder <= endInorder && *rootInorder != rootValue) rootInorder++; int leftLength = rootInorder - startInorder; int* leftPreorderEnd = startPreorder + leftLength; if (leftLength > 0) { root->LChild = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1); }//左子树 if(leftLength < endPreorder - startPreorder) { root->RChild = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder); }//右子树 return root; } Node* Construct(int* preorder, int* inorder, int length) { if (preorder == NULL || inorder == NULL || length <= 0) return NULL; return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1); } //倒序输出 void TraverseTreePostorder(Node* proot) { if(proot == NULL) return; if(proot->LChild != NULL) TraverseTreePostorder(proot->LChild); if(proot->RChild != NULL) TraverseTreePostorder(proot->RChild); cout << proot->data << " "; } //层序输出 void Print(Node* T) { int parentSize = 1, childSize = 0; queue <Node*> q; Node* temp; q.push(T); temp = q.front(); cout << temp->data << " "; while (!q.empty()) { q.pop(); if (temp->LChild != NULL) { q.push(temp->LChild); childSize++; } if (temp->RChild != NULL) { q.push(temp->RChild); childSize++; } parentSize--; if (parentSize == 0) { parentSize = childSize; childSize = 0; } if (!q.empty()) { temp = q.front(); cout << temp->data << " "; //控制输出格式 } } } int main() { int n, i; while (scanf("%d", &n) != EOF) { int preorder[100]; int inorder[100]; for (i = 0; i < n; i++) cin >> preorder[i]; for (i = 0; i < n; i++) cin >> inorder[i]; Node* pRoot = Construct(preorder, inorder, n); // TraverseTreePostorder(pRoot); // cout << endl; //倒序输出 Print(pRoot); } return 0; }