BinTree 到 BinTree 的括号表示
我正在编写一个程序,它接受二叉树的字符串表示形式并从中创建一棵树。该代码对我来说完全有意义,但它仍然无法完成它应该做的事情。
这是一些代码:
(((()B(C))D(E))F(G))J(()K((L)M(T)))
private static BinTree<String> findRoot(String s){
String tree = s;
int i = 0;
int count = 0;
String root;
if(tree.equalsIgnoreCase("()")){
return null;
}
if(tree.length()==3){
return new BinTree<String>(Character.toString(tree.charAt(1)));
}
while(i<tree.length()){
if(tree.charAt(i)=='('){
count++;
}
if(tree.charAt(i)==')'){
count--;
if(count==0){
i++;
root = Character.toString(tree.charAt(i));
return new BinTree<String>(root, findRoot(tree.substring(1, i-1)), findRoot(tree.substring(i+1)));
}
}
i++;
}
return null;
}
I'm writing a program that takes in a string representation of a binary tree and creating a tree out of it. The code makes complete sense to me but it still won't do what it should.
Here is some code:
(((()B(C))D(E))F(G))J(()K((L)M(T)))
private static BinTree<String> findRoot(String s){
String tree = s;
int i = 0;
int count = 0;
String root;
if(tree.equalsIgnoreCase("()")){
return null;
}
if(tree.length()==3){
return new BinTree<String>(Character.toString(tree.charAt(1)));
}
while(i<tree.length()){
if(tree.charAt(i)=='('){
count++;
}
if(tree.charAt(i)==')'){
count--;
if(count==0){
i++;
root = Character.toString(tree.charAt(i));
return new BinTree<String>(root, findRoot(tree.substring(1, i-1)), findRoot(tree.substring(i+1)));
}
}
i++;
}
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过检查每次调用
findRoot()
的s
值来开始调试。该代码看起来不错,但我感觉您的substring()
参数中存在相差一的错误。Start debugging by inspecting the values of
s
for each call tofindRoot()
. The code looks good, except that I have a feeling you have off-by-one errors in yoursubstring()
parameters.我发现,当您找到根时,您会在根左侧的所有内容和右侧的所有内容上递归调用 findRoot 。或者无论如何。对左子节点的调用会删除它周围的括号,但右子节点不会。当您通过检查字符串长度 3 找到叶节点时,您希望保留括号。因此左孩子调用应该是:
findRoot(tree.substring(0, i)
。I see that when you've found your root, you recursively call findRoot on the everything left of the root and everything on the right. Or meant to anyway. The call for the left child removes the parenthesis around it, but the right one doesn't. Seeing as you find a leaf node by checking for string length of 3, you want to keep the parens. So the left child call should be:
findRoot(tree.substring(0, i)
.抱歉:我的低代表不允许我直接发表评论,所以我需要通过这个答案提出我的问题。
是
(((()B(C))D(E))F(G))J(()K((L)M(T)))
一个示例字符串输入 - 二叉树的表示。
如果是这样,您能否以文字形式提供该树的一部分。只要几片叶子就可以了。
Sorry: my low rep doesn't allow me to comment directly, so I need to ask my question via this answer.
Is
(((()B(C))D(E))F(G))J(()K((L)M(T)))
an example string input - representation of a binary tree.
If so, can you provide in word form just a bit of the tree. Just a couple of the leaves would do the trick.