[英][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.