import java.util.HashMap; import java.util.Scanner;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main { private static HashMap<Character,Integer>mp; private static int nodeIndex; public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNextLine()) { String[]strs=sc.nextLine().split(" "); char[]preorder=strs[0].toCharArray(); char[]inorder=strs[1].toCharArray(); mp=new HashMap<>(); nodeIndex=0; for(int i=0;i<preorder.length;i++) { mp.put(inorder[i],i); } TreeNode root=buildTree(preorder,inorder); dfs(root); System.out.println(""); } }
public static class TreeNode { char val; TreeNode left; TreeNode right; TreeNode(){} TreeNode(char val) { this.val=val; } } private static TreeNode buildTree(char[]preorder,char[]inorder) { int n=preorder.length; return build(preorder,inorder,0,n-1); } private static TreeNode build(char[]preorder,char[]inorder,int l,int r) { int n=preorder.length; if(nodeIndex>=n||l>r)return null; char rootVal=preorder[nodeIndex]; TreeNode root=new TreeNode(rootVal); ++nodeIndex; int mid=mp.get(rootVal); root.left=build(preorder,inorder,l,mid-1); root.right=build(preorder,inorder,mid+1,r); return root; } private static void dfs(TreeNode node) { if(node==null)return; dfs(node.left); dfs(node.right); System.out.print(node.val); }
}
|