[HELP]带有BST递归插入的Java StackOverflow错误

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

themoonsky2009 回答:[HELP]带有BST递归插入的Java StackOverflow错误

if (node.key < root.key) {
    root.left = insertRec(root.left);
} else if( node.key > root.key) {
    root.right = insertRec(root.right);
}

您无需再次设置父级。递归的想法是前进而不是后退。

希望这会有所帮助。祝你好运。

,

已修复:我的构造函数每次都与insert方法一起为left right和parent创建元素。

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;
}
本文链接:https://www.f2er.com/3134104.html

大家都在问