1020. Tree Traversals 解析

我是直接由后序 和中序建树 然后 层序遍历。

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector <int> post;
vector <int> in;

int N, Count = 0;

struct Node {
	int data;
	Node * L;
	Node * R;
};

typedef Node * Tree;


Tree BuildTree(int inst,int ined, int postst ,int posted) {
	Tree t = new Node;
#ifdef _DEBUG
	cout << "in: " << inst << " " << ined ;
	cout << " Post: " << postst << " " << posted << endl;
#endif
	if (postst <= posted) {
		t->data = post[posted];
#ifdef _DEBUG
		cout << post[posted] << endl;
#endif
		int L = 0; int R = 0; int tempI = 0;
		bool isFind = false, isLR = false;
		for (int i = inst; i <= ined; i++) {
			if (in[i] == post[posted]) {
				isFind = true;
				isLR = true;
				tempI = i;
			}

			if (!isLR) L++;
			else R++;
		}
		R--;
#ifdef _DEBUG
		cout << "L " << L << " R " << R << endl;
#endif
		if (isFind) {
			t->L = BuildTree(inst, tempI - 1, postst, postst + L - 1);
			t->R = BuildTree(tempI + 1, ined, postst + L, posted - 1);
		}
		else return NULL;
	}
	else t = NULL;

	return t;

}

void PreOrder(Tree T) {
	if(T){
		cout << T->data << " ";
		PreOrder(T->L);
		PreOrder(T->R);
	}
}

vector <int> s;
void LevelOrder(Tree T) {
	queue <Tree> q;
	Tree temp;
	if (T) {
		q.push(T);
		while (!q.empty()) {
			temp = q.front();
//			cout << q.size() << endl;
			s.push_back(temp->data);
			q.pop();
			if (temp->L) q.push(temp->L);
			if (temp->R) q.push(temp->R);
		}
	}
}

int main() {
	int  temp;
	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> temp;
		post.push_back(temp);
	}
	for (int i = 0; i < N; i++) {
		cin >> temp;
		in.push_back(temp);
	}
	Tree T = BuildTree(0,N-1,0,N-1);
	//PreOrder(T);
	LevelOrder(T);
	
	for (int i = 0; i < s.size() - 1; i++) {
		cout << s[i] << " ";
	}
	cout << s[s.size()- 1] << endl;

	system("pause");

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值