gpt4 book ai didi

java - [HELP]BST 递归插入时 Java StackOverflow 错误

转载 作者:行者123 更新时间:2023-12-01 21:47:57 24 4
gpt4 key购买 nike

我正在尝试用递归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处显示循环

最佳答案

已修复:我的构造函数每次都与插入方法一起为左右和父级创建元素。

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;
}

关于java - [HELP]BST 递归插入时 Java StackOverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com