[英]Building a BinaryTree from an InOrder String Representation
我得到了一個像這樣的字符串:(((.D.)B,)A((:F(!H!))C(!G!))),其中從來沒有任何空格。 A '!' 意味着節點的那一側沒有孩子。 為了形象化,前面提到的字符串看起來像: https://i.stack.imgur.com/WywYm.png
我必須有一個構造函數,它可以調用遞歸方法來通過傳入字符串來構建樹,這就是我在這里所擁有的:
public BinaryTree(String tree) {
//build the tree from the inOrder representation of the tree
//in the inOrder representation an empty tree is ! and a non-empty tree is (leftdataright)
if(tree.charAt(0) == '!') root = null;
root = buildTree(tree).root;
}
從這里開始,我通過私有 BuildTree 方法進入,該方法應該使用遞歸並返回對完全組裝樹的根的引用。 我的代碼是:
private BinaryTree buildTree(String tree) {
char data = tree.charAt(0);
BinaryTree b1;
BinaryTree b2;
if(tree.charAt(0) == '!') return new BinaryTree();
b1 = buildTree(tree.substring(1, tree.length()));
b2 = buildTree(tree.substring(1, tree.length()));
return new BinaryTree(b1, data, b2);
}
我想我感到困惑的是 InOrder 表示,在您深入到字符串之前,您不會遇到整棵樹的根。 我當前的代碼沒有做任何事情,而且我完全不知道如何在不立即了解根的情況下完成此操作。 如果有人可以更好地解釋這一點,讓我更接近解決方案,請告訴我。 謝謝。
這樣的事情怎么樣:
private static BinaryTree buildTree(String tree) {
try {
return buildTree(new StringReader(tree));
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
}
}
private static BinaryTree buildTree(Reader in) throws IOException {
char c = (char)in.read();
if (c == '!') {
return null;
} else if (c != '(') {
throw new IOException("Syntax error");
}
BinaryTree left = buildTree(in);
char data = (char)in.read();
BinaryTree right = buildTree(in);
c = (char)in.read();
if (c != ')') {
throw new IOException("Syntax error");
}
return new BinaryTree(left, data, right);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.