小红书的笔试题
题目记不全了,反正就是提供层序序列和中序序列。输出是前序序列和后序序列,以及从左到右的输出叶子节点。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static Map<Integer,Integer> map;
public static Node build(int[] c, int[] z){
Node root = create(c,z,0,c.length);
return root;
}
public static Node create(int[] c,int[] z,int s,int e){
int minI = c.length;
// System.out.println(s+" : "+e);
int curr = s;
for (int i =s; i < e; i++) {
if(minI > map.get(z[i])){
minI = map.get(z[i]);
curr = i;
}
}
if(minI == c.length){
return null;
}
// System.out.println("index:"+minI);
Node n = new Node(c[minI]);
n.left = create(c,z,s,curr);
n.right = create(c,z,curr+1,e);
return n;
}
public static void prePrint(Node root){
if(root !=null) {
System.out.print(root.data + " ");
prePrint(root.left);
prePrint(root.right);
}
}
public static void postPrint(Node root){
if(root !=null) {
postPrint(root.left);
postPrint(root.right);
System.out.print(root.data + " ");
}
}
public static void leafPrint(Node root){
if(root !=null) {
if(root.left == null && root.right == null){
System.out.print(root.data + " ");
}
leafPrint(root.left);
leafPrint(root.right);
}
}
public static void main(String[] args) {
String s1 = "3 5 4 2 6 7 1";
String s2 = "2 5 3 6 4 7 1";
// Scanner sc = new Scanner(System.in);
// String s1 = sc.nextLine();
// String s2 = sc.nextLine();
map = new HashMap<Integer, Integer>();
String[] items = s1.split(" ");
String[] items2 = s2.split(" ");
int[] c = new int[items.length];
int[] z = new int[items.length];
for (int i = 0; i < items.length; i++) {
c[i] = Integer.parseInt(items[i]);
z[i] = Integer.parseInt(items2[i]);
map.put(c[i],i);
}
Node root = build(c,z);
leafPrint(root);
System.out.println();
prePrint(root);
System.out.println();
postPrint(root);
System.out.println();
}
}
class Node{
public int data;
Node left;
Node right;
public Node(int d){
this.data = d;
}
}