이 프로그램을 작성하여 BST를 만들었습니다. 사용자가 트리를 만들고 BST에서 값을 검색 할 수 있지만이 번호를 찾는 데 필요한 반복 횟수를 출력하는 데 도움이 필요합니다. 어떻게하는지. "iterations"라는 변수를 만들었지 만이 숫자를 수집하는 방법을 만드는 방법으로 붙어 있습니다. 모든 아이디어를 내 프로그램에서 어떻게 구현할 것인가, 그 번호를 찾아서 인쇄하는 방법은 무엇입니까?이진 검색 트리에서 값을 찾는 데 필요한 반복 횟수를 표시 (출력)하는 방법은 무엇입니까?
import java.util.Scanner;
/* 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();
}
}
3 가지 유형의 주문이 아닌 검색 방법에 대해 원하는 점이 있습니다. 내가 권고 한대로 노력했지만, 반복 횟수는 0에 상관없이 유지됩니다. 왜 그런가? –
질문을 편집하여 시도한 코드를 포함시킬 수 있습니까? 나는 그것을 살펴볼 것이다. – Keara
질문 섹션에서 프로그램을 편집했고 주문 방법을 지웠으므로 검색에서 값을 찾기 위해 필요한 반복 횟수를 인쇄하는 반복 방법을 구현하는 방법에 대한 도움이 필요합니다. –