【问题标题】:[HELP]Java StackOverflow Error with BST Recursive Insert[帮助]Java StackOverflow 错误与 BST 递归插入
【发布时间】:2020-03-05 15:46:21
【问题描述】:

我正在尝试使用递归插入方法编写 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

【问题讨论】:

    标签: java recursion insert binary-search-tree


    【解决方案1】:

    已修复:我的构造函数每次都使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多