import java.util.Scanner;
class Node {
char value;
Node left;
Node right;
int signal;
public Node() {}
public Node(char value, Node left, Node right, int signal) {
super();
this.value = value;
this.left = left;
this.right = right;
this.signal = signal;
}
public int getValue() {
return value;
}
public void setValue(char value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
public class Main {
static int k = 0;
private static void layerOrder(Node root) {
if(root == null)
return ;
Node[] q = new Node[k];
char[] r = new char[k];
int start = 0, end = 1;
q[start] = root;
while(start < end && start < k) {
r[start] = q[start].value;
if(q[start].left != null)
q[end++] = q[start].left;
if(q[start].right != null)
q[end++] = q[start].right;
start++;
}
System.out.println(new String(r));
}
private static Node findLayers(char[] prc, char[] inc, int low, int high) {
if(low > high)
return null;
Node root = new Node();
char tmp_root = prc[k++];
root.setValue(tmp_root);
int position_root_in_In = -1;
for( int i = low; i <= high; i++ ) {
if(tmp_root == inc[i]) {
position_root_in_In = i;
break;
}
}
Node l = findLayers(prc,inc,low,position_root_in_In-1);
Node r = findLayers(prc,inc,position_root_in_In+1,high);
root.setLeft(l);
root.setRight(r);
return root;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
k = 0;
String pr = sc.nextLine();
String post = sc.nextLine();
int len = pr.length();
char[] prc = pr.toCharArray();
char[] inc = post.toCharArray();
char[] layer = new char[len];
Node root = new Node();
root.setValue(prc[0]);
root.setLeft(null);
root.setRight(null);
Node tree = findLayers(prc,inc,0,len-1);
layerOrder(tree);
}
}
}
给一个二叉树的前序和中序序列,求二叉树的层序序列
最新推荐文章于 2025-04-22 16:15:42 发布