华中科技大学 二叉树遍历(java)

题目描述
二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入描述:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出描述:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
示例1
输入
复制
ABC
BAC
FDXEAG
XDEFAG
输出
复制
BCA
XEDGAF
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.* ;
public class Main
{
	static char[] pre;
	static char[] in;
	public static void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String str;
			while((str=br.readLine()) != null) {
				 pre = str.toCharArray();
				 in = br.readLine().toCharArray();
				 BiTNode root = contruct(0, pre.length-1, 0, in.length-1);
				 printPostOrder(root);
				 System.out.println();
			}				 
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
	public static BiTNode contruct(int ps, int pe, int is, int ie) {
		if(ps > pe) return null;
		char value = pre[ps];
		int index = is;
		while(is < ie && in[index] != value) {
			index++;
		}
		BiTNode node = new BiTNode(value);
		node.lchild = contruct(ps+1, ps+index-is, is, index-1);
		node.rchild = contruct(ps+index-is+1, pe, index+1, ie);
		return node;
	}
	public static void printPostOrder(BiTNode root) {
		if(root != null) {
			printPostOrder(root.lchild);
			printPostOrder(root.rchild);
			System.out.print(root.val);
		}
	}
}
class BiTNode{
	char val;
	BiTNode lchild, rchild;
	BiTNode(char data){
		val = data;
	}
}



发布了252 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104251278