PAT 1086 Tree Traversals Again 二叉树的遍历

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.pic1
Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1

思路分析:

在示例中
Push入栈的顺序是 1,2,3,4,5,6,是访问二叉树的先序遍历
Pop出栈顺序是 3,2,4,1,6,5,是中序遍历二叉树
于是问题变成已知先序遍历 中序遍历,求二叉树的后序遍历

AC代码如下

#include<cstdio>
#include<string.h>
#include<stack>
using namespace std;
int N;
const int maxn=50;
int preorder[maxn];
int inorder[maxn];
struct Node{
	int val;
	Node *lchild,*rchild;
};
Node *create(int preL,int preR,int inL,int inR){
	
	if(preL > preR){
		return NULL;
	}
	Node *root = new Node;	
	root->val = preorder[preL];
	//找到先序中的根在中序遍历中的位置 
	int k;
	for(k=inL;k<=inR;k++)
		if(inorder[k]==preorder[preL])
			break;
	int numLeft= k - inL;//左子树结点个数 
	root->lchild=create(preL+1,preL+numLeft,inL,k-1);
	root->rchild=create(preL+numLeft+1,preR,k+1,inR);
	
	return root;
}
int cnt=0;
void postVisit(Node *p){
	
	if(p!=NULL){
		postVisit(p->lchild);
		postVisit(p->rchild);
		printf("%d",p->val);
		cnt++;
		if(cnt<N) printf(" ");
	}
	
}
//给出先序和中序遍历 重建二叉树 
int main(){
	stack<int>st;
	char str[5];
	int pre_index=0,in_index=0;
	scanf("%d",&N);
	for(int i=0;i<2*N;i++){
		scanf("%s",str);
		if(strcmp("Push",str)==0){
			int x;
			scanf("%d",&x);
			st.push(x);
			preorder[pre_index++]=x;
		}
		else{
			inorder[in_index++]=st.top();
			st.pop();
		}
	}
	/*
	for(int i=0;i<N;i++)
	{
		printf("%d %d\n",preorder[i],inorder[i]);
	}*/
	Node *root=create(0,N-1,0,N-1);
	postVisit(root);
	return 0;
} 

ps
这题我一个写法错了好久T.T

int k;
	for(int k=inL;k<=inR;k++)
		if(inorder[k]==preorder[preL])
			break;

就是这种写法,里面的k是正确的值,外层的k一直是0,然后卡死了…
错误原因 循环内部的局部变量在for循环结束内存会释放

发布了9 篇原创文章 · 获赞 3 · 访问量 259

猜你喜欢

转载自blog.csdn.net/weixin_39666736/article/details/96911310