由前序中序序列求后序序列(PAT (Advanced Level)1086 Tree Traversals Again,树)

题目大意是给出非递归中序遍历一棵树的过程,让你输出后序序列。
如:
在这里插入图片描述
这是样例的树
很妙的是,在非递归中序遍历过程中,顺序push的数字就是先序遍历数组,顺序pop的数字就是中序遍历数组。
怎么得到后序遍历数组呢?其实这道题根本不需要建树,只需进行一些递归即可。递归函数写法如下:
在这里插入图片描述
参数中的preL,inL,postL是指这次过程中需要用到的pre,in,post序列的部分的最左边元素的下标。需要注意的是,下标从0开始,而n是从1开始数的,传参不要写错。
完全代码:

package codeforces;

import java.util.Scanner;
import java.util.Stack;

public class test {
	static int pre[],in[],post[],root;
	static Stack<Integer> tmp;
	public static void main(String args[]) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		//pre=in=post=new int[n];//这样写出了大·问·题,让我改了半天。。。
		pre=new int[n];
		in=new int[n];
		post=new int[n];
		tmp=new Stack<Integer>();
		sc.nextLine();
		String str;
		int top1=0,top2=0,num=1;
		int T=2*n;
		while(T>0) {
			T--;
			str=sc.next();
			//System.out.println(str);
			if(str.equals("Push")) {
				num=sc.nextInt();
				pre[top1++]=num;
				tmp.push(num);
			}else if(str.equals("Pop")){
				//System.out.println(str);
				in[top2++]=tmp.pop();
			}
			sc.nextLine();
		}
		solve(0,0,0,n);
		for(int i=0;i<n;i++) {
			if(i==0) {
				System.out.print(post[i]);
			}else {
				System.out.print(" "+post[i]);
			}
		}
	}
	public static void solve(int preL,int inL,int postL,int n) {
		if(n==0) {//当进入了一个节点的不存在某边子树(即这个节点没有这一边的子树)时,结束
			return;
		}
		if(n==1) {//当进入了一个节点的只有一个节点的某边子树时,
		//传进去的参数坐标使pre、in都指向了同一个值,把这个值赋给post[postL]即可。
			post[postL]=pre[preL];
			return;
		}
		root=pre[preL];//preL指向的元素一定是这次递归时的树的根结点。
		//把它赋给这次用到的post的范围的最后一个值(因为是后·根序列嘛)
		post[postL+n-1]=root;
		int i=0;
		for(;i<n;i++) {//这一步是要找到这次递归的树的根结点在in中的位置,
		//以便确定这次递归的树的左子树和右子树。
			if(in[inL+i]==root) {//注意下标是intL+i而不是i
				break;
			}
		}
		int L=i,R=n-L-1;
		solve(preL+1,inL,postL,L);//遍历这个子树的左子树
		solve(preL+L+1,inL+L+1,postL+L,R);//遍历这个子树的右子树
	}
}

不知不觉写了好多注释…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值