이진 검색 트리 (사용자 입력 사용)를 구현하고 값을 검색하여 실제로이 값을 찾는 데 필요한 반복 횟수를 출력하는 프로그램을 만들 수없는 것처럼 보입니다. 반복 수를 반환하는 getLastIterationCount()라는 메서드를 만들었지 만 주 메서드에서 인쇄하려고 할 때 'System.out.println (getLastIterationCount())'줄에 오류가 발생합니다. ; '. 내 방법이 올바른 위치에 있지 않다고 생각하지만 실종 된 것이 확실하지 않습니다. 어떻게하면이 프로그램을 만들 수있는 아이디어가 있습니까?BST에서 값을 찾는 데 필요한 반복 횟수를 출력하는 방법은 무엇입니까?
/* 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();
}
}
나는 당신의 충고에 따라, 고마워하지만 내 'System.out.println (getLastIterationCount());' Netbeans에 의해 잘못된 것으로 밑줄이 그어져 있습니다. 내 메소드 'getLastIterationCount()'가 잘못된 위치에있어 내 print 문이 함수 호출을 인식하지 못하게합니까? –
안녕하세요 내 대답을보고 그것을 시도하십시오! –
@humanbeing 네, 특정 트리 인스턴스에 대한 카운트를 얻으려면'bst.getLastIterationCount()'를 호출해야합니다. 하지만 더 큰 문제는 계산 논리와 관련이 있다고 생각합니다. –