递归树构造和堆栈溢出错误

时间:2016-10-12 12:23:55

标签: java recursion binary-search-tree stack-overflow

我正在尝试使用递归方法创建一个包含1,000,000个节点的二叉搜索树,每个节点包含一个0到1,000,000的数字。根必须包含500,000,其左子包含250,000,右子包含750,000。此模式将继续每个节点,直到使用所有数字。我需要返回root以允许程序搜索特定的数字。但是,我不断收到堆栈溢出错误。当我将数字更改为0和2以更小的比例进行测试时,它会继续以2而不是1来返回节点。任何想法?

public static BTNode treeMaker(int minimum, int maximum)
{
    int currentNum = (minimum + maximum)/2;
    BTNode node = new BTNode(currentNum, null, null);
    if(minimum == maximum)
        return node;
    else
    {
        node.setLeft(treeMaker(minimum, currentNum - 1));
        node.setRight(treeMaker(currentNum + 1, maximum));
        return node;
    }
}

编辑:以下是BTNode类:

public class BTNode 
{
   private static int data;
   private static BTNode left, right;

   public BTNode(int newData, BTNode newLeft, BTNode newRight)
   {
       data = newData;
       left = newLeft;
       right = newRight;
   }

   public static BTNode getLeft()
   {
       return left;
   }

   public static BTNode getRight()
   {
       return right;
   }

   public static int getData()
   {
       return data;
   }

   public static void setLeft(BTNode newLeft)
   {
      left = newLeft;
   }

   public static void setRight(BTNode newRight)
   {
       right = newRight;
   }
}

1 个答案:

答案 0 :(得分:0)

无法通过java.lang.StackOverflowError,但发现以下错误:它会一直返回

您已在类级别定义了字段(data, left, right)和函数,而这些应在实例级别定义。当您在类级别保留字段时,它们的值会针对每个节点进行更新,并且您将获得正在处理的最后一个值,即2

请尝试以下操作(字段位于实例级别):

公共类BTNode {

private int data;
private BTNode left;
private BTNode right;

private BTNode(int newData, BTNode newLeft, BTNode newRight) {
    data = newData;
    left = newLeft;
    right = newRight;
}

public BTNode getLeft() {
    return left;
}

public BTNode getRight() {
    return right;
}

public int getData() {
    return data;
}

public void setLeft(BTNode newLeft) {
    left = newLeft;
}

public void setRight(BTNode newRight) {
    right = newRight;
}

public static BTNode getBT(int minimum, int maximum) {
    int currentNum = (minimum + maximum) / 2;
    BTNode node = new BTNode(currentNum, null, null);
    if (minimum == maximum)
        return node;
    else {
        node.setLeft(BTNode.getBT(minimum, currentNum - 1));
        node.setRight(BTNode.getBT(currentNum + 1, maximum));
        return node;
    }
}

public static void main(String[] args) {
    BTNode node = BTNode.getBT(0, 2);
    System.out.println(node.getData());
}

}