L2-3 玩转二叉树 (25分)

在这里插入图片描述

7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

输出样例:

4 6 1 7 5 3 2

不知道说啥了 超无语的一道题 觉得没错但是一直段错误

段错误部分:int k; for(int k;......)这样写是不对的 再加上下边还要用到k值所以还一定要在外部声明k 所以正确写法只有下边这样了:

int k;//在中序序列中寻找k
	for(k = inl; k <= inr; k++)
	{
    
    
		if(in[k] == pre[prel])
		{
    
    
			break;
		}
	}
#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <map>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn = 33;
struct node
{
    
    
	int data;
	node* lchild;
	node* rchild;
};
int pre[maxn],in[maxn],n;
node* creat(int prel, int prer,int inl,int inr)
{
    
    
	if(prel > prer) 
	{
    
    
		return NULL;
	}
	node* root = new node;
	root->data = pre[prel];//取出根节点
	int k;//在中序序列中寻找k
	for(k = inl; k <= inr; k++)
	{
    
    
		if(in[k] == pre[prel])
		{
    
    
			break;
		}
	}
	int numl = k - inl;
	root->rchild = creat(prel + 1, prel + numl, inl, k-1);
	root->lchild = creat(prel + numl + 1, prer, k + 1, inr); 
	return root;
}

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) cout << " ";
		if(now->lchild != NULL) q.push(now->lchild);
		if(now->rchild != NULL) q.push(now->rchild);
	}
}
int main()
{
    
    
	cin >> n;
	for(int i = 0; i < n; i++)
	{
    
    
		cin >> in[i];
	}
	for(int i = 0; i < n; i++)
	{
    
    
		cin >> pre[i];
	}
	node* root = creat(0, n-1, 0, n-1);
	layerorder(root);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/moumoumouwang/article/details/109661214