sicily 1156 Binary tree

            前序输入二叉树

#include<iostream>

#include <memory.h>

using namespace std;



struct node

{

	char content;

	int left;

	int rigth;

};

node tree[1001];



void pre_print(node);



int main()

{	

	bool isroot[1001]; //记录是否根节点

	int id[1001]; //节点编号

	int cases, n, left, right, k;

	char c;

	while (cin >> cases)

	{

		memset(isroot, true, sizeof(isroot));



		k = 0;

		for (int i = 0; i < cases; i++)

		{

			cin >> n >> c >> left >> right;

			tree[n].left = left;

			tree[n].rigth = right;

			tree[n].content = c;

			isroot[left] = isroot[right] = false; //左儿子和右儿子都不是根节点

			id[k++] = n;		

		}



		//查找根节点

		for (int i = 0; i < k; i++)

			if (isroot[id[i]])

			{

				pre_print(tree[id[i]]);

				cout << endl;

				break;

			}

	}

	return 0;

}



void pre_print(node root)

{	

	cout << root.content;

	if (root.left != 0)

		pre_print(tree[root.left]);

	if (root.rigth != 0)

		pre_print(tree[root.rigth]);

}

你可能感兴趣的:(binary)