国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

1020. Tree Traversals 解析

2019-11-11 02:00:08
字體:
供稿:網(wǎng)友

我是直接由后序 和中序建樹 然后 層序遍歷。

#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;}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 东至县| 泊头市| 双城市| 上饶市| 德兴市| 东台市| 宿州市| 东宁县| 西吉县| 乡城县| 南京市| 庆阳市| 托里县| 宜黄县| 永胜县| 漳浦县| 商河县| 锦州市| 西贡区| 拉萨市| 临湘市| 望都县| 凤庆县| 柳江县| 堆龙德庆县| 安图县| 安乡县| 韶关市| 高尔夫| 龙游县| 蒙山县| 西青区| 南郑县| 乐亭县| 昭觉县| 石阡县| 广灵县| 云霄县| 永安市| 浦县| 普洱|