根據二叉樹的先序序列和中序序列還原二叉樹並列印後序序列

期待一片自己的藍天發表於2014-05-31
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

struct Node
{
	int value;
	Node *left;
	Node *right;
	Node(int value)
	{
		this->value = value;
		left = right = NULL;
	}
};

bool bNotTree = false;
Node* RebuildTree(int *preOrder, int *inOrder, int length)
{
	if (length <= 0)
		return NULL;
	if (length == 1)
	{
		if (*preOrder != *inOrder)
		{
			bNotTree = true;
			return NULL;
		}
		return new Node(*preOrder);
	}

	int i;
	for (i = 0; *preOrder != inOrder[i] && i < length; ++i);
	if (i == length)
	{
		bNotTree = true;
		return NULL;
	}
	Node *root = new Node(*preOrder);
	root->left = RebuildTree(preOrder+1,inOrder,i);
	root->right = RebuildTree(preOrder + i + 1, inOrder + i + 1,length-i-1);
	return root;
}

void PrintTree(Node* root)
{
	if (root)
	{
		PrintTree(root->left);
		PrintTree(root->right);
		cout << root->value << " ";
	}
}

int main()
{
	int preOrder[1000];
	int inOrder[1000];

	int n;
	while (cin >> n)
	{
		int i;
		bNotTree = false;
		for (i = 0; i < n; ++i)
		{
			cin >> preOrder[i];
		}
		for (i = 0; i < n; ++i)
		{
			cin >> inOrder[i];
		}
		Node *tmp = RebuildTree(preOrder, inOrder, n);
		if (bNotTree)
			cout << "No" << endl;
		else
		{
			PrintTree(tmp);
			cout << endl;
		}
	}
	return 0;
}

相關文章