1020. Tree Traversals (25)

考察树的建立,以及树的遍历

#include<vector>
#include<iostream>
#include<map>
#include<queue>

typedef struct Node
{
	int value;
	Node* left;
	Node* right;
	Node(Node* _left = NULL, Node* _right = NULL, int _value = -1)
		:left(_left),right(_right),value(_value){};
};
std::map<int, int> postMap;
std::map<int, int> inMap;

void ReleaseTree(Node* root)
{
	if(root == NULL) return;
	ReleaseTree(root->left);
	ReleaseTree(root->right);
	delete root;
}

int FindMaxIdxInPost(const std::vector<int>&inOrder, int s, int t)
{
	int max = 0;
	for(int i = s; i <= t; ++i)
	{
		if(max < postMap[inOrder[i]])
			max = postMap[inOrder[i]];
	}
	return max;
}
void BuildTree(Node* &root, const std::vector<int>& postOrder, int p_s, int p_t, 
				const std::vector<int>& inOrder, int in_s, int in_t)
{
	if(p_s > p_t || in_s > in_t)
	{
		root = NULL;
		return;
	}
	root = new Node;
	root->value = postOrder[p_t];
	int inRootIdx = inMap[root->value];
	if(inRootIdx != in_s && inRootIdx != in_t)//has left tree & right tree
	{
		int p_maxIdx = FindMaxIdxInPost(inOrder, in_s, inRootIdx-1);
		BuildTree(root->left, postOrder, p_s, p_maxIdx, inOrder, in_s, inRootIdx-1);
		BuildTree(root->right, postOrder, p_maxIdx+1, p_t-1, inOrder, inRootIdx+1, in_t);
	}
	else if(inRootIdx != in_s && inRootIdx == in_t)//only left tree
	{
		BuildTree(root->left, postOrder, p_s, p_t-1, inOrder, in_s, in_t-1);
	}
	else if(inRootIdx == in_s && inRootIdx != in_t)//only right tree
	{
		BuildTree(root->right, postOrder, p_s, p_t-1, inOrder, in_s+1, in_t);
	}

}

void LevelTravel(Node* root)
{
	std::queue<Node*> q;
	if(root != NULL)
	{
		printf("%d", root->value);
		q.push(root->left);
		q.push(root->right);
	}
	else return;
	while( !q.empty() )
	{
		Node* node = q.front();
		q.pop();
		if(node == NULL) continue;
		printf(" %d", node->value);
		q.push(node->left);
		q.push(node->right);
	}
	printf("\n");
}
int main()
{
	int n;
	while( scanf("%d", &n) != EOF )
	{
		std::vector<int> postOrder(n), inOrder(n);
		postMap.clear();
		inMap.clear();
		for(int i = 0; i < n; ++i)
		{
			scanf("%d", &postOrder[i]);
			postMap[postOrder[i]] = i;
		}
		for(int i = 0; i < n; ++i)
		{
			scanf("%d", &inOrder[i]);
			inMap[inOrder[i]] = i;
		}

		Node* tree;
		BuildTree(tree, postOrder, 0, n-1, inOrder, 0, n-1);
		LevelTravel(tree);
		ReleaseTree(tree);
	}
	return 0;
}


 

你可能感兴趣的:(pat,ZJU)