題目描述:
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order 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 (≤30), the total number of nodes in the binary tree. The second line gives the postorder 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 level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
題目的意思就是,給出一個二叉樹的後序和中序的遍歷序列,給出它的層次遍歷結果。
思路:題目的關鍵是對二叉樹的恢復。給出後序序列可以確定出根節點,之後在中序序列中找到相應的根節點就可以劃分出左子樹和右子樹,對二叉樹進行遞歸創建。遞歸函數在編寫的時候,一定要先找好遞歸邊界和遞歸表達式。
遇到的問題:在編寫代碼的過程中,遇到的最大的問題是參數值的傳遞,左子樹右子樹劃分的邊界值沒有找對,正確的劃分如下圖所示:
還有一個很愚蠢的錯誤就是,在對二叉樹進行層次遍歷的時候,我!居!然!忘!記!了!對左右子樹是否爲空的判斷,就是每次考完試總是要把腦子丟在考場上幾天。
代碼如下:
// PATA1020.cpp: 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include "iostream"
#include "algorithm"
#include "queue"
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int postdata[50], indata[50];
node* Create(int pl,int pr,int il,int ir)
{
//遞歸結束條件
if (pl > pr)
return NULL;
//遞歸表達式
//首先,從後序遍歷中找到根節點
int newroot = postdata[pr];
node* newndrt = new node;
newndrt->data = newroot;
int k; //記錄root下標的位置
//其次,從中序遍歷中找到相同的值(查找中序序列從頭至尾)
for (int i = il; i <= ir; i++)
{
if (indata[i] == newroot)
{
k = i;
break;
}
}
int llength = k - il;//記錄左子樹的結點個數
newndrt->lchild = Create(pl, pl + llength - 1, il, k - 1);
newndrt->rchild = Create(pl+llength, pr-1, k+1, ir);
return newndrt; //得返回節點地址呀
}
//先序遍歷
void postorder(node *root)
{
if (root == NULL)
return;
cout << root->data << " ";
postorder(root->lchild);
postorder(root->rchild);
}
void levelroder(int n,node* root) //對二叉樹進行層次遍歷
{
//首先,將根節點加入隊列
queue<node*> qnodes;
qnodes.push(root); int cnt = 0;
while (!qnodes.empty())//當隊列非空時
{
node* crt = qnodes.front();//取出隊首元素,都是以無參函數的形式存在的
if (cnt != n-1)
cout << crt->data << " ";
else
cout << crt->data;
cnt++;
if(crt->lchild!=NULL)
qnodes.push(crt->lchild);
if (crt->rchild != NULL)
qnodes.push(crt->rchild);
qnodes.pop(); //該元素出棧
}
}
int main()
{
int n;
//接收數據輸入
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> postdata[i];
}
for (int i = 0; i < n; i++)
{
cin >> indata[i];
}
//對二叉樹進行遞歸構建
node* root = new node;
root = Create(0, n-1, 0, n-1);
levelroder(n,root);
system("pause");
return 0;
}