uva 122

原题

模拟构造一棵二叉树的过程 , 我的方法就是构造一个题目中所说的pair结构,

也可以当做树的结点, 包括数值, 两个子节点指针, 以及路径

先把所有输入收集起来, 按路径的长度排序, 然后按顺序插入(其实这个顺序就是最后的中序遍历的顺序了)

插入的时候, 有几种情况可以判断出是 not complete, 不过我这里写得不是很整洁, 思路有点乱

主要就是, 先看在寻路的过程中如果中间有NULL的结点, 就是false

如果寻到终点, 发现终点已经有结点值了, 即重复给的pair, 那么也是not complete


一开始用的顺序存储的树结构, 后来才意识到有可能会出现高度256的树, 这样不可能用数组来存得下了..

这样的稀疏的树只能用链式存储

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <list>
#include <cassert>
#include <iomanip>

using namespace std;
const int MAXN = 50000;

/*
uva 122
 虽然只有不超过256个结点, 但深度也可能达到256, 这样就无法用数组存储了
因此 应该用链式存储的二叉树 

*/
struct Pair{
	int value;
	string path;
	Pair * left, * right;
};

bool operator<(const Pair &p1, const Pair & p2){
	if( p1.path.length()!=p2.path.length() ) return p1.path.length() < p2.path.length();
	else return p1.path < p2.path;
}


vector<Pair> vec;
vector<int>  ans;

void DeleteTree(Pair * T){
	if( T->left ) DeleteTree(T->left);
	if( T->right ) DeleteTree(T->right);
	free(T);
}

bool solve(){
	Pair * root = NULL;
	for(int i=0; i<vec.size(); i++){
		Pair p = vec[i];
		Pair * Node = root;
		int j = 0; 
//		cout << p.path << " " << p.path.length() << endl;
		for( j=0; p.path.length()>0 && j<p.path.length()-1; j++){
			if( Node==NULL ){
				return false;
			}
			if( p.path[j]=='L' ){
				Node = Node->left;
			}else{
				Node = Node->right;
			}
		}
		if( p.path.length()==0 ){
			Node = (Pair*)malloc(sizeof(Pair));
			root = Node;
		}else if( Node==NULL ){
			return false;
		}else{
			if( p.path[j]=='L' && Node->left==NULL ){
				Node->left = (Pair*)malloc(sizeof(Pair));
				Node = Node->left;
			}else if( p.path[j]=='R' && Node->right==NULL ){
				Node->right = (Pair*)malloc(sizeof(Pair));
				Node = Node->right; 
			}else{
				return false;	
			}
		}
		Node->value = p.value;
		Node->left = Node->right = NULL;
		ans.push_back(p.value);
	}
	DeleteTree(root);
	return true;
}

int main(){
	Pair p;
	char input[500];
	while( scanf("%s",input)!=EOF ){
		ans.clear();
		vec.clear();
		do{
			char * ptr = strchr(input,',');
			*strchr(input,')') = '\0';
			*ptr = '\0';
			p.path = (ptr+1);
			p.value = atoi(input+1);
			vec.push_back(p);
		}while( scanf("%s",input) && strcmp(input,"()")!=0 );
		sort(vec.begin(),vec.end());
		if( solve() ){
			int i;
			for(i=0; i<ans.size()-1; i++){
				cout << ans.at(i) << " ";
			}
			cout << ans.at(i) << endl;
		}else{
			cout << "not complete" << endl;
		}
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值