hihocoder: 后序遍历


根据前序和中序的遍历顺序,把后序遍历求出来

之前在leetcode做过,重新敲了一遍,熟悉递归的操作就是了

import java.io.*;
import java.util.*;


public class Main{

	static char[] pre;
	static char[] mid;
	static BitTree tree;
	static HashMap map = new HashMap<>();
	public static void main(String[] args) throws Exception{
		Scanner cin = null;
		cin = new Scanner(System.in);
		cin = new Scanner(new FileInputStream(new File("in")));
		String str = cin.next();
		pre = str.toCharArray();
		str = cin.next();
		mid = str.toCharArray();
		init();
		BitTree root = rebuildTree(0, pre.length, 0, pre.length);
		postTrace(root);
		System.out.println();
	}

	private static void init(){
		map.clear();
		for(int i = 0; i < mid.length; ++i){
			map.put(mid[i], i);	
		}
	}

	private static BitTree rebuildTree(int preStart, int 
				preEnd, int midStart, int midEnd){
		if(midStart < midEnd){
			int cur = map.get(pre[preStart]);
			BitTree tree = new BitTree(pre[preStart]);
			tree.left = rebuildTree(preStart + 1, preStart + cur - midStart, midStart, cur);
			tree.right = rebuildTree(preStart + cur - midStart + 1, preEnd, cur + 1, midEnd);
			return tree;
		}
		return null;
	}
	
	private static void postTrace(BitTree tree){
		if(tree != null){
			postTrace(tree.left);
			postTrace(tree.right);
			System.out.print(tree.value);
		}
	}
	
	private static class BitTree{
		public char value;
		public BitTree left, right;

		public BitTree(char value){
			this.value = value;
		}
	}
}


你可能感兴趣的:(hihocoder)