A1020 Tree Traversals (25分)

一、技术总结

  1. 第一步数据结构的定义,和存放二叉树序列的数组
  2. 第二步定义层次序列的遍历函数,是广度搜索的算法进行,先内部自己定义一个队列,然后把根结点push进入队列,只要队列不为空就遍历while,同时内部定义一个结点然后弹出队首结点,然后打印数据域。然后如果左右结点不为空,把左右结点push进入队列。
  3. 第三步编写create函数,即根据后序和中序队列进行二叉树的创建。首先postL如果大于postR,就返回NULL,然后创建根结点,再把根结点的数据域放入进去。int k,使用for循环找到中序遍历中根结点,break。int numLeft = k - inL;再对于左右指针,create,根据先序遍历和后序遍历进行参数赋值。

二、参考代码

#include<cstdio>
#include<queue>
using namespace std;
const int maxn = 50;
struct Node{
	int data;
	Node* lchild;
	Node* rchild;
};
int in[maxn], post[maxn];
int n;
int num = 0;
void LayerOrder(Node* root){
	queue<Node*> q;
	q.push(root);
	while(!q.empty()){
		Node* now = q.front();
		q.pop();
		printf("%d", now->data);
		num++;
		if(num < n) printf(" ");
		if(now->lchild != NULL) q.push(now->lchild);
		if(now->rchild != NULL) q.push(now->rchild);
	}
}
Node* create(int postL, int postR, int inL, int inR){
	if(postL > postR){
		return NULL;
	}
	Node* root = new Node;
	root->data = post[postR];
	int k;
	for(k = inL; k < inR; k++){
		if(in[k] == post[postR]){
			break;
		}
	}
	int numLeft = k - inL;
	root->lchild = create(postL, postL+numLeft-1, inL, k - 1);
	root->rchild = create(postL+numLeft, postR-1, k+1, inR);
	return root;
}
int main(){
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	Node* root = create(0, n-1, 0, n-1);
	LayerOrder(root);
	return 0;
}
posted @ 2020-02-14 22:09  睿晞  阅读(130)  评论(0编辑  收藏  举报