gpt4 book ai didi

java - 如何输出在 BST 中查找值所需的迭代次数?

转载 作者:行者123 更新时间:2023-12-02 11:52:32 25 4
gpt4 key购买 nike

我似乎无法让我的程序实现二叉搜索树(使用用户输入)并搜索一个值,以打印出实际找到该值所需的迭代次数。我创建了一个名为“getLastIterationCount()”的方法,它返回迭代次数,但是当我想在主方法中打印它时,我在“System.out.println(getLastIterationCount());”行上收到错误。 '。我认为我的方法不正确,但我不确定缺少什么。我有什么想法可以让这个程序发挥作用吗?

     /* Class Node */
class Node


{
Node left, right;
int data;



/* Constructor */
public Node(int n)
{
left = null;
right = null;
data = n;
}

/* Function to get data from node */
public int getData()
{
return data;
}

/* Function to get left node */
public Node getLeft()
{
return left;
}

/* Function to get right node */
public Node getRight()
{
return right;
}
}

/* Class BST */
class BST

{

private Node root;
private int iterations;
/* Constructor */
public BST()
{
root = null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private Node insert(Node node, int data)
{
if (node == null)
node = new Node(data);
else
{
if (data <= node.data)
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}


/* Functions to search for an element */
public boolean search(int val)
{
iterations=0;
iterations++;
return search(root, val);
}



/* Function to search for an element recursively */
private boolean search(Node r, int val)
{
iterations=0;
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval){
r = r.getLeft();
}

else if (val > rval){
r = r.getRight();
}

else
{
found = true;
break;
}
found = search(r, val);

}

return found;
}

public int getLastIterationCount(){
return iterations;
}


}
/* Class LinkedListBST */
public class LinkedListBST
{


public static void main(String[] args)

{


Scanner scan = new Scanner(System.in);
/* Creating object of BST */
BST bst = new BST();
System.out.println("Linked List Binary Search Tree Test\n");
char ch;
/* Accept input */
do
{
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );



System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);


} while (ch == 'Y'|| ch == 'y');
System.out.println("\nEnter an element to be searched: ");
Scanner sc = new Scanner(System.in);
System.out.println("Search result : " + bst.search(sc.nextInt()));

System.out.println(getLastIterationCount()); //ISSUE IS HERE

sc.close();

}

}

最佳答案

您正在访问方法 getLastIterationCount(),但没有该对象。请使用 bst.getLastIterationCount() 调用它

关于java - 如何输出在 BST 中查找值所需的迭代次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47784348/

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