PAT A-1020的一个问题

/*重构二叉树的思想是先到后序遍历或者是先序遍历中先寻找根节点,然后在根据根据点的内容到中序遍历中找根节点的位置*/
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
const int N = 35;

typedef struct node {
	int data;
	struct node *lchild, *right;
}node,*pnode;

void BFS(pnode root);
pnode create(int postL, int postR, int inL, int inR);
int post[N], in[N];//后序遍历和中序遍历
int main() {
	int n = 0;
	cin >> n;
	for (int i = 0; i < 2*n; i++) {
		if (i <= 6) cin >> post[i];
		else cin >> in[i - 7];
	}
	pnode root = create(0, n - 1,0,n-1);
	BFS(root);
	system("pause");
	return 0;
}

pnode create(int postL,int postR,int inL,int inR) {//递归还原二叉树
	if (postL > postR) {
		return NULL;
	}
	pnode root = (pnode)malloc(sizeof(node));
	root->data = post[postR];//首先到后序遍历中找到跟节点
	int k = 0;
	while (in[k] != post[postR])k++;//找到根节点在中序遍历中的位置

	int num = k - inL;//左子树规模
	root->lchild = create(postL,postL+num-1,inL,k-1);//根据中序遍历得到的位置,左边为该根节点的左子树
	root->right = create(postL+num,postR-1 ,k+1,inR);//中序遍历根节点的右边为其右子树
	return root;
}

void BFS(pnode root) {
	queue<pnode> q;
	q.push(root);
	while (!q.empty()) {
		pnode tem = q.front();
		printf("%d", tem->data);
		if (tem!=q.back()) {
			cout << " ";
		}
		q.pop();
		if (tem->lchild != NULL)q.push(tem->lchild);
		if (tem->right != NULL)q.push(tem->right);
	}
	cout << endl;
}

这段代码放到pat和牛客都会报段错误和程序内存过大的问题,

定位到:

for (int i = 0; i < 2*n; i++) {

        if (i <= 6) cin >> post[i];

        else cin >> in[i - 7];

    }

这个循环这里,我只是想用一个循环输入两个而已,然后就报错了,换成两个循环就能够通过了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值