import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static void main(String[]strs){
String preOrder ="12453";
String inOrder ="42513";
Node root = houXu(preOrder,inOrder);
bianli(root);
}
public static void bianli(Node root){
if (root == null){
return ;
}
bianli(root.leftNode);
bianli(root.rightNode);
System.out.println(root.value);
}
public static Node houXu(String preOrder,String inOrder){
if (preOrder.length()==0 || inOrder.length()==0){
return null;
}
Node root = new Node(Integer.parseInt(String.valueOf(preOrder.charAt(0))));
int index = inOrder.indexOf(preOrder.charAt(0));
String sonLeftOrd = inOrder.substring(0,index);
String sonLeftPre = preOrder.substring(1,sonLeftOrd.length()+1);
String sonrightnOrd =inOrder.substring(index+1);
String sonrightPre = preOrder.substring(sonLeftOrd.length()+1);
root.leftNode= houXu(sonLeftPre,sonLeftOrd);
root.rightNode= houXu(sonrightnOrd,sonrightPre);
return root;
}
}
Node类文件:
public class Node {
int value;
Node leftNode;
Node rightNode;
Node(int value){
this.value = value;
this.leftNode = null;
this.rightNode = null;
}
}