[英][HELP]Java StackOverflow Error with BST Recursive Insert
我正在尝试使用递归插入方法编写 BST,但似乎我被困在程序没有跳出的行上。
如果在从 Main 调用 insert 时对元素键进行了排序,它可以工作,如果它们没有排序,它就不起作用,我不知道为什么。
public static void main(String[] args) {
BST bst = new BST();
bst.insert(2,"Val_0");
bst.insert(1,"Val_1");
}
public class BSTNode {
public int key;
public String val;
public BSTNode left, right, parent;
public BSTNode(int key, String val) {
this.key = key;
this.val = val;
this.left = new BSTNode();
this.right = new BSTNode();
this.parent = new BSTNode();
}
public BSTNode() {
// TODO Auto-generated constructor stub
}
}
public class BST {
private BSTNode root;
public BST() {
this.root = null;
}
public void insert(int key, String val) {
root = insertRec(new BSTNode(key,val));
}
private BSTNode insertRec(BSTNode node) {
if (root == null) {
root = node;
return root;
}
if (node.key < root.key) {
root.left = insertRec(root.left);
root.left.parent = root;
}if( node.key > root.key) {
root.right = insertRec(root.right);
root.left.parent = root;
}
return node;
}
}
错误:线程“main”中的异常 java.lang.StackOverflowError,调试器在 node.key < root.key 处显示一个循环
if (node.key < root.key) {
root.left = insertRec(root.left);
} else if( node.key > root.key) {
root.right = insertRec(root.right);
}
您不需要再次设置父级。 递归的想法是 go 向前而不是向后重新分配。
希望这可以帮助。 祝你好运。
已修复:我的构造函数每次都使用 insert 方法为左右和父级创建元素。
public class BSTNode {
public int key;
public String val;
public BSTNode left, right, parent;
public BSTNode(int key, String val) {
this.key = key;
this.val = val;
this.left = null;
this.right = null;
this.parent = null;
}
------//------------ 也改变了一些方法:
public void insert(int key, String val) {
root = insertRec(root, new BSTNode(key,val));
}
private BSTNode insertRec(BSTNode currentParent,BSTNode node) {
if (currentParent == null) {
return node;
}
if (node.key < currentParent.key) {
currentParent.left = insertRec(currentParent.left,node);
currentParent.left.parent = currentParent;
}if(node.key > currentParent.key) {
currentParent.right = insertRec(currentParent.right,node);
currentParent.right.parent = currentParent;
}
return currentParent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.