【发布时间】:2022-01-04 04:55:19
【问题描述】:
我正在开发一个程序,该程序接受代表前缀格式二进制表达式的字符串(例如 (A(B(C)(D))(E(F)(G))) )。我一直坚持算法的一部分,以根据来自单独堆栈的括号将数据添加到节点(在 A 代表根之后,'('表示左节点,而 ')' 后跟 '(' 表示右节点。在我点击以下代码之前,我的代码似乎运行良好:
if (focus != null && val == '(') {
char nodeVal = tree.pop();
Node node = new Node(nodeVal);
focus = root;
while(focus != null) {
focus = focus.leftNode;
}
focus = node;
它通过“if (focus != null)”,但是当它到达 while 循环时,它要么返回错误,要么不添加新节点,要么创建一个无限循环(基于我的一些变化一直在尝试。如果有帮助,方法的完整代码如下:
public void constructTree(String input) {
for(int i = input.length()-1; i>=0; i--) {
if(input.charAt(i) == '(' || input.charAt(i) == ')') {
paren.push(input.charAt(i));
}
else {
tree.push(input.charAt(i));
}
}
while(!paren.isEmpty()) {
char val = paren.pop();
Node focus = root;
Node parent;
if (val == ')' && root == null) {
throw new InvalidTreeSyntax("Your tree cannot be empty");
}
if (root == null) {
char nodeVal = tree.pop();
Node node = new Node(nodeVal);
root = node;
}
if (focus != null && val == '(') {
char nodeVal = tree.pop();
Node node = new Node(nodeVal);
focus = root;
while(focus != null) {
focus = focus.leftNode;
}
focus = node;
}
else if (focus != null && val == ')' && paren.peek()== '(' || paren.peek() == null) {
char nodeVal = tree.pop();
Node node = new Node(nodeVal);
paren.pop();
while(focus!= null) {
focus = focus.rightNode;
}
focus = node;
}
}
}
我确信这是一个简单的错误,但是在肚子里塞满了火鸡并且睡眠不足之后,我已经脑死亡,需要一些帮助!
【问题讨论】:
-
我看到了对局部变量“focus”(形式为“focus = node”)的几个赋值,然后你什么都不做,此时变量在外部的末尾消失了while 循环。最终结果是所有确定“焦点”值的代码根本不执行任何操作。
-
这很有意义,但是我无法摆脱内部 while 循环,甚至无法达到焦点 = 节点的出现。如果我将 focus = node 放入内部 while 循环,我会得到一个无限循环,其中没有任何内容被添加到根节点
-
那么你有一个节点,它的左指针被搞砸了。鉴于您对创建的“新节点”没有做任何可见的事情,很难知道是什么。根点的leftNode指向什么?你确定链的末端设置为空吗?您发布的任何内容都无法回答这个问题。
标签: java binary-tree nodes