- 求二叉树的先序序列
- 2016-04-29 21:52:08 @
// input code here
2 条评论
-
不退 LV 8 @ 2018-05-03 23:23:17
两年后的相遇……
题主现在应该已经是大神了吧…… -
2018-04-26 15:44:10@
你要的java,但我觉得可能你已经用不上了
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { static FileReader fr; static char[] mQueue; static char[] eQueue; public static Scanner getInput() { return new Scanner(System.in); } // public static Scanner getInput() throws IOException { // File f = new File("input.txt"); // fr = new FileReader(f); // Scanner sc = new Scanner(fr); // // return sc; // } public static void input() throws IOException { Scanner sc = getInput(); String s1, s2; s1 = sc.nextLine(); s2 = sc.nextLine(); mQueue = s1.toCharArray(); eQueue = s2.toCharArray(); if (fr != null) { fr.close(); } } static class Node{ char key; public Node left; public Node right; public Node(char key) { this.key = key; } } public static Node check(int mb, int me, int eb, int ee) { if (mb > me || eb > ee) { return null; } Node node = new Node(eQueue[ee]); for (int len = 0; len <= me - mb; len ++) { int index = len + mb; if (mQueue[index] == node.key) { node.left = check(mb, index - 1, eb, eb + len - 1); node.right = check(index + 1, me, len + eb, ee - 1); break; } } return node; } static String encode(Node root) { if (root == null) { return ""; } String s = new String(String.valueOf(root.key)); s = s + encode(root.left) + encode(root.right); return s; } public static String algorithm() { Node root = check(0, mQueue.length - 1, 0, eQueue.length - 1); String result = encode(root); return result; } public static void output(String result) { System.out.println(result); } public static void main(String args[]) throws IOException { input(); String result = algorithm(); output(result); } }
- 1