hihocoder: 뒷차례 두루 훑어보기

1552 단어 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;
		}
	}
}

좋은 웹페이지 즐겨찾기