您的位置:首页 > 编程语言

编程之美--重建二叉树

2012-10-28 12:18 281 查看
/**
* 重建二叉树 给两个序列:pre: a b d c e f in : d b a e c f 把这个二叉树创建出来
*/
public class ReBuilderTree {
private Entry root;

public void rebuild(String pre, String in) {
root = rebuildHelper(pre, in);
}

private Entry rebuildHelper(String pre, String in) {
if (pre == null || pre.length() == 0 || in == null || in.length() == 0)
return null;
char c = pre.charAt(0);
int t = in.indexOf(c); // 找到前充的第一个在中充中的位置
Entry newEntry = new Entry(c, null, null);
newEntry.left = rebuildHelper(pre.substring(1, t + 1),
in.substring(0, t + 1));
newEntry.right = rebuildHelper(pre.substring(t + 1),
in.substring(t + 1));
return newEntry;
}

private void preOrder(Entry e) {

}

static class Entry {
char val;
Entry left;
Entry right;

public Entry(char val, Entry left, Entry right) {
this.val = val;
this.left = left;
this.right = right;
}
}

public static void main(String args[]) {
String pre = "abdcef", in = "dbaecf";
ReBuilderTree object = new ReBuilderTree();
object.rebuild(pre, in);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: