码迷,mamicode.com
首页 > 其他好文 > 详细

根据二叉树的先序序列和中序序列还原二叉树并打印后序序列

时间:2014-06-03 00:43:00      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   a   int   

#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;
}

根据二叉树的先序序列和中序序列还原二叉树并打印后序序列,布布扣,bubuko.com

根据二叉树的先序序列和中序序列还原二叉树并打印后序序列

标签:c   class   blog   code   a   int   

原文地址:http://blog.csdn.net/nyist327/article/details/27736239

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!