1110. Complete Binary Tree 解析

刚开始像之前那个题一样,看到只有20个结点,想着不大,丢到数组里面看有没有空结点。发现不对。。。

后面改了方法,用广度遍历,遍历到空结点的时候,看看是不是所有结点都遍历完了,来判断。

注意输入的时候,不要像我一样用char在读入。数字有两位的。。哎。。。

#include <iostream>
#include <cstring>
#include <queue>
#include <string>

#define MAX 25
#define null -1

using namespace std;

struct Node {
	int left;
	int right;
};

Node Tree[MAX];
bool isVis[MAX];
vector <int> tempNode;

int n;
int last = 0;

bool Check(int root) {
	queue <int> q;
	bool isEmpty = false;

	if (root == null)
		return true;

	q.push(root);
	tempNode.push_back(root);

	while (!q.empty()) {
		int temp = q.front();
		q.pop();
		last = temp;
		if (Tree[temp].left == null) {
			break;
		}
		else {
			q.push(Tree[temp].left);
			tempNode.push_back(Tree[temp].left);
		}

		if (Tree[temp].right == null) {
			break;
		}
		else {
			q.push(Tree[temp].right);
			tempNode.push_back(Tree[temp].right);
		}
	}

	if (tempNode.size() != n)
		return false;

	return true;
}

int str2int(string s) {
	int sum = 0;
	for (int i = 0; i < s.size(); i++) {
		sum *= 10;
		sum += s[i] - '0';
	}
	return sum;
}


int main() {
	cin >> n;

	memset(isVis, false, sizeof(isVis));

	string temp1, temp2;
	for (int i = 0; i < n; i++) {
		cin >> temp1 >> temp2;
//		cout << temp1 << temp2 << endl;
		if (temp1[0] == '-')
			Tree[i].left = null;
		else {
			Tree[i].left = str2int(temp1);
			isVis[Tree[i].left] = true;
		}

		if (temp2[0] == '-')
			Tree[i].right = null;
		else {
			Tree[i].right = str2int(temp2);
			isVis[Tree[i].right] = true;
		}
	}

	int root = null;
	for (int i = 0; i < n; i++) {
		if (!isVis[i]) {
			root = i;
			break;
		}
	}

	bool isCT = Check(root);
	
	if (isCT)
		cout << "YES " << tempNode[n-1] << endl;
	else
		cout << "NO " << root << endl;

	return 0;

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值