算法学习【11】—— 1156. Binary tree

题目来源:http://soj.me/1156

1156. Binary tree

Description

Your task is very simple: Given a binary tree, every node of which contains one upper case character (‘A’ to ‘Z’); you just need to print all characters of this tree in pre-order.

Input

Input may contain several test data sets.

      For each test data set, first comes one integer n (1 <= n <= 1000) in one line representing the number of nodes in the tree. Then n lines follow, each of them contains information of one tree node. One line consist of four members in order: i (integer, represents the identifier of this node, 1 <= i <= 1000, unique in this test data set), c (char, represents the content of this node described as above, ‘A’ <= c <= ‘Z’), l (integer, represents the identifier of the left child of this node, 0 <=  l <= 1000, note that when l is 0 it means that there is no left child of this node), r (integer, represents the identifier of the right child of this node, 0 <=  r <= 1000, note that when r is 0 it means that there is no right child of this node). These four members are separated by one space.

      Input is ended by EOF.

      You can assume that all inputs are valid. All nodes can form only one valid binary tree in every test data set.

Output

For every test data set, please traverse the given tree and print the content of each node in pre-order. Characters should be printed in one line without any separating space.

Sample Input

34 C 1 31 A 0 03 B 0 011000 Z 0 031 Q 0 22 W 3 03 Q 0 0

Sample Output

CABZQWQ

Problem Source

ZSUACM Team Member


思路:最多1000个节点,求前序遍历结果。由于输入数据规则,用数组实现是第一个想到的方法。也容易实现。

代码:

#include <iostream>
#include <cstring>

using namespace std;

struct treeNode 
{
	int leftChild;
	int rightChild;
	char data;
};

treeNode arrayTree[1001];

void prePrint(int rootId)
{
	if (rootId != 0)
	{
		cout << arrayTree[rootId].data;
		prePrint(arrayTree[rootId].leftChild);
		prePrint(arrayTree[rootId].rightChild);
	}
}

int main()
{
	int nodeNum;
	treeNode tempInput;
	int inputId;
	int rootId;
	bool nodeExit[1001];
	bool beenChild[1001];

	while (cin >> nodeNum)
	{
		memset(nodeExit, false, sizeof(nodeExit));
		memset(beenChild, false, sizeof(beenChild));

		while (nodeNum--)
		{
			cin >> inputId >> tempInput.data >> tempInput.leftChild >> tempInput.rightChild;
			arrayTree[inputId] = tempInput;
			nodeExit[inputId] = true;
			beenChild[tempInput.leftChild] = true;
			beenChild[tempInput.rightChild] = true;
		}

		for (rootId = 1; rootId < 1001; rootId++)
		{
			if (nodeExit[rootId] && !beenChild[rootId])
			{
				break;
			}
		}
	
		prePrint(rootId);
		cout << endl;
	}

	return 0;
}


你可能感兴趣的:(算法学习【11】—— 1156. Binary tree)