PAT (Advanced Level) 1020. Tree Traversals (25)

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

这道题说的很直白,没有什么绕绕弯弯的,就是树的建立(create),然后说是树的层序遍历(BFS

容易写错的是create这部分,刚开始提交几次一直显示段错误,后来检查才发现:

for(int k=inL;k<=intR;i++)   ,我习惯性的写成从i=0到i<=n了。。。

第二处错误就是root->lchild=create(posL,posL+numLeft-1,inL,k-1);     root->rchild=create(posL+numLeft,posR,k+1,inR);

这两句话,要么是递归的下标写错,要么就是忘记赋值了,只想到递归。。。。

在BFS里面要注意的就是,必须判断它的左(右)子树是否是NULL,非空才能加入队列~


#include<cstdio>
#include<queue>
#include<algorithm>

using namespace std;

const int maxn = 50;

int ino[maxn], pos[maxn];
int n;

struct Node {
	int data;
	Node* lchild;
	Node* rchild;
};

Node* create(int posL, int posR, int inL, int inR) {
	if (posL > posR) {
		return NULL;
	}

	Node* root = new Node;
	root->data = pos[posR];
	int k;
	for (k = inL; k <=inR ; k++) {
		if (pos[posR] == ino[k]) {
			break;
		}
	}

	int numLeft = k - inL;
	root->lchild=create(posL, posL + numLeft - 1, inL, k - 1);
	root->rchild=create(posL + numLeft, posR - 1, k + 1, inR);
	return root;
}


void BFS(Node* root) {
	queue<Node*> q;
	q.push(root);
	int tt = 0;
	while (!q.empty()) {
		Node* top = q.front();
		q.pop();
		printf("%d", top->data);
		tt++;
		if (tt == n) {
			printf("\n");
		}
		else {
			printf(" ");
		}
		if (top->lchild!=NULL) { q.push(top->lchild); }
		if (top->rchild!=NULL) { q.push(top->rchild); }
	}

}

int main() {
	scanf("%d", &n);

	for (int i = 0; i < n; i++) {
		scanf("%d", &pos[i]);
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", &ino[i]);
	}
	Node* root = create(0, n - 1, 0, n - 1);
	BFS(root);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值