首页 > 代码库 > POJ 1577 Falling Leaves 二叉树题解

POJ 1577 Falling Leaves 二叉树题解

给出按最底层叶子节点到根节点的数据,然后要求重建树,前序输出最终建的树。

都是两个基本操作解决:

1 二叉树插入操作

2 前序遍历

简单题目了。


#include <stdio.h>
#include <string>
#include <algorithm>
#include <vector>
using std::vector;
using std::string;

const int MAX_B = 1024;
char buf[MAX_B];
int id = 0, len = 0;

inline char getFromBuf()
{
	if (id >= len)
	{
		len = fread(buf, 1, MAX_B, stdin);
		id = 0;
	}
	return buf[id++];
}

void getStrFromBuf(string &n)
{
	char a = getFromBuf();
	while ((a == ' ' || a == '\n') && len) a = getFromBuf();
	
	n.clear();
	while ((a != ' ' && a != '\n') && len)//老是写&&,错成||
	{
		n.push_back(a);
		a = getFromBuf();
	}
}

struct Node
{
	char alpha;
	Node *left, *right;
	explicit Node (char a = ' ') : alpha(a), left(NULL), right(NULL) {}
};

Node *insertNode(Node *root, char a)
{
	if (!root) return new Node(a);

	if (a < root->alpha) root->left = insertNode(root->left, a);
	else root->right = insertNode(root->right, a);
	return root;
}

void printTree(Node *r)
{
	if (r)
	{
		putchar(r->alpha);
		printTree(r->left);
		printTree(r->right);
	}
}

void releaseTree(Node *r)
{
	if (r)
	{
		releaseTree(r->left);
		releaseTree(r->right);
		delete r; r = NULL;
	}
}

int main()
{
	string s;
	while (true)
	{
		getStrFromBuf(s);
		if (len == 0 || s == "$") break;

		vector<string> vstr;
		while (s != "*" && s != "$")
		{
			vstr.push_back(s);
			getStrFromBuf(s);
		}
		Node *root = NULL;
		for (int i = (int)vstr.size() - 1; i >= 0 ; i--)
		{
			for (int j = 0; j < (int)vstr[i].size(); j++)
			{
				root = insertNode(root, vstr[i][j]);
			}
		}
		printTree(root);
		releaseTree(root);
		putchar('\n');
	}
	return 0;
}