题目链接:http://hihocoder.com/problemset/problem/1049
题目描述:
没错!小Ho在这一周遇到的问题便是:给出一棵二叉树的前序和中序遍历的结果,还原这棵二叉树并输出其后序遍历的结果。
每个测试点(输入文件)有且仅有一组测试数据。
每组测试数据的第一行为一个由大写英文字母组成的字符串,表示该二叉树的前序遍历的结果。
每组测试数据的第二行为一个由大写英文字母组成的字符串,表示该二叉树的中序遍历的结果。
对于100%的数据,满足二叉树的节点数小于等于26。
对于每组测试数据,输出一个由大写英文字母组成的字符串,表示还原出的二叉树的后序遍历的结果。
思路:
根据前序、中序结果,构造树,输出后序结果。 以前在leet做过这题。。
思路就是根据 前序确定的节点值pre[i] 查找它在中序中的位置 idx,根据这个位置将中序划分成两块[left,idx-1]、[idx+1,right],
再根据这两块的size分别确定下一个要在前序中的值:pre[i+1] 、和pre[i+(idx-1-left+1)+1]。
算法:
import java.util.Scanner; public class Main { public static void main(String[] args) { Main m = new Main(); m.handleInput(); } public void handleInput() { Scanner sc = new Scanner(System.in); char[] pre = sc.next().trim().toCharArray(); char[] in = sc.next().trim().toCharArray(); TreeNode root = create(pre, 0, in, 0, in.length - 1); post(root); } public TreeNode create(char pre[], int i, char in[], int left, int right) { if(i>=pre.length||right<left) return null; if (right == left) return new TreeNode(pre[i]); TreeNode node = new TreeNode(pre[i]); int idx = search(in, pre[i]); TreeNode leftChild = create(pre, i + 1, in, left, idx - 1); TreeNode rightChild = create(pre, i + idx - left + 1, in, idx + 1, right); node.left = leftChild; node.right = rightChild; return node; } public int search(char n[], char target) { for (int i = 0; i < n.length; i++) { if (n[i] == target) return i; } return -1; } class TreeNode { TreeNode left, right; Character val; public TreeNode(Character val) { this.val = val; } } public void post(TreeNode root) { if (root == null) return; post(root.left); post(root.right); System.out.print(root.val); } }