树的层次遍历,Trees on the level, UVA 122

题目链接:https://vjudge.net/problem/UVA-122

题解:题意就是按题目要求建立二叉树,然后进行BFS,我在uDebug上进行了测试,都通过了,但是仍然没法通过vjudge上的测试例,找不到问题在哪儿?希望有大神能帮助看看,多谢,多谢。

代码:(注意没有AC)

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<vector>

using namespace std;



struct node {
	int data = -1;
	node *left = NULL;
	node *right = NULL;
};

node * root = new node();

string dir_s;
string s;

bool insert(node *r, int value, char dir, int remain) {
	
	if (remain == -1) {
		if (r->data != -1)return false;
		r->data = value;
	}
	else {
		if (dir == 'L') {
			if (r->left == NULL)r->left = new node();
		}
		else {
			if (r->right == NULL)r->right = new node();
		}
		return insert(dir == 'L' ? r->left : r->right, value, dir_s[dir_s.length() - remain ], remain - 1);
	}
	return true;
}

queue<node> q;

void clear() {
	while (!q.empty()) {
		q.pop();
	}
	root = new node();
}

int main() {

	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	int flag = 1;
	while (cin>>s) {

		if (s == "()"||flag==0) {

			vector<int> v;
			q.push(*root);
			while (!q.empty()) {
				node p = q.front(); q.pop();
				if (p.data == -1) {
					flag = 0;
					break;
				}
				v.push_back(p.data);
				if (p.left != NULL)q.push(*p.left);
				if (p.right != NULL)q.push(*p.right);
			}
			if (flag == 0)cout <<"not complete";
			else {		
				for (int i = 0; i < v.size()-1; i++)cout << v[i] << " ";
				cout << v[v.size() - 1];
			}
			cout << endl;
			//print
			clear();
			flag = 1;
			continue;
		}
		else {
			dir_s = s.substr(s.find_first_of(',') + 1, (s.find_first_of(')') - s.find_first_of(',')) - 1);
			
			string num = s.substr(1,s.find_first_of(',')-1);
			stringstream ss(num);
			int nu = 0;
			ss >> nu;

			flag=insert(root, nu, dir_s[0], dir_s.length() - 1);
		}
	}


	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值