class Baum{ String wert; Baum left, right; static String preorder=""; static Baum erzeuge(String inorder){ if (preorder.equals("")) return null; if (inorder.equals("")) return null; // if (! inorder.contains(preorder.substring(0,1))) return null; Baum k = new Baum();
String inh = preorder.substring(0,1); System.out.println("inh "+inh); k.wert = inh; int stelle = inorder.indexOf(inh); String links = ""; for (int i=0;i<stelle ; i++) links = links + inorder.substring(i,i+1); String rechts = ""; for (int i=stelle+1;i<inorder.length() ; i++) rechts = rechts + inorder.substring(i,i+1); preorder = preorder.substring(1,preorder.length()); k.left = erzeuge((links)); k.right = erzeuge((rechts)); return k; } static void inord(Baum b){ if (b!=null) {
inord(b.left); System.out.print(b.wert); inord(b.right); }
} static void postord(Baum b){ if (b!=null) { postord(b.left); postord(b.right); System.out.print(b.wert); }
} public static void main(String args[]){ String inorder = "ADCGBHEFI"; preorder = "CDAFGHBEI"; Baum b; b = erzeuge((inorder)); System.out.println(); inord(b); System.out.println(); postord(b); } }