中国大学MOOC-陈越、何钦铭-数据结构-2018秋 03-树2 List Leaves (25 分)

#include "pch.h"
#include 
#include 

#define MAX 10

using namespace std;

class Node {
public:
	int index;
	int lchild;
	int rchild;
};

Node node[MAX];
int isRoot[MAX] = { 0 };

int main()
{
	int N;

	cin >> N;
	cin.ignore();

	for (int i = 0; i < N; i++) {

		char left, right;

		cin >> left >> right;
		cin.ignore();

		node[i].index = i;
		if (left != '-') node[i].lchild = left - '0';
		else node[i].lchild = -1;

		if (right != '-') node[i].rchild = right - '0';
		else node[i].rchild = -1;

	}

	for (int i = 0; i < N; i++) {

		int child;

		if (node[i].lchild != -1) {

			child = node[i].lchild;
			isRoot[child] = 1;

		}

		if (node[i].rchild != -1) {

			child = node[i].rchild;
			isRoot[child] = 1;

		}

	}

	//查找树根

	int root;

	for (int i = 0; i < N; i++) {

		if (isRoot[i] == 0) {

			root = i;
			break;

		}
	}

	//层序遍历

	queue q;
	q.push(node[root]);

	int count = 0;

	while (!q.empty()) {

		int child;
		Node current_node = q.front();
		q.pop();

		if (current_node.lchild != -1) {

			child = current_node.lchild;
			q.push(node[child]);

		}

		if (current_node.rchild != -1) {

			child = current_node.rchild;
			q.push(node[child]);

		}

		if (current_node.lchild == -1 && current_node.rchild == -1) {

			if (count == 0) {

				cout << current_node.index;
				count++;

			}
			else {

				cout << ' ' << current_node.index;

			}

		}

	}



	return 0;
}

你可能感兴趣的:(PTA)