Ich schreibe ein Java-Programm, um das k-kleinste Element in einem BST zu finden.Java-Programm, um das k-kleinste Element in einem BST zu finden
Ich habe einige andere Beiträge zu dieser Frage auf Stack-Überlauf gegangen und habe ihre Lösungen durchlaufen, aber ich kann nicht verstehen, was das Problem mit meinem Code ist. Wenn jemand könnte mir bitte sagen, warum mein Programm nichts druckt.
//Program to find the kth smallest element in the BST
public class KthSmallestElement {
static Node root;
//method to insert a key
Node insertRec(Node root, int key)
{
//if the tree is empty
if(root == null)
{
root = new Node(key);
return root;
}
//otherwise recur down the tree
else
{
if(key > root.key)
{
root.right = insertRec(root.right, key);
}
else
{
root.left = insertRec(root.left, key);
}
return root;
}
}
//This method is for calling the insertRec() method
Node insert(int key)
{
root = insertRec(root, key);
return root;
}
//This method is for doing the inorder traversal of the tree
void kthSmallest(Node root, int k)
{
int counter = 0;
if(root == null)
return;
else
{
kthSmallest(root.left, k);
counter++;
if(counter == k)
{
System.out.println(root.key);
}
kthSmallest(root.right, k);
}
}
//main method
public static void main(String[] args)
{
KthSmallestElement tree = new KthSmallestElement();
Node root = null;
root = tree.insert(20);
root =tree.insert(8);
root =tree.insert(22);
root =tree.insert(4);
root= tree.insert(12);
root =tree.insert(10);
root =tree.insert(14);
tree.kthSmallest(root, 3);
}
}
Und meine Knotenklasse ist wie folgt:
//Class containing left and right child of current node and key value
public class Node {
int key;
Node left, right, parent;
//Constructor for the node
public Node(int item){
key = item;
left = right = parent= null;
}
}
Es ist das Problem nicht Druck anything.That ist. Ok, ich bin nicht so gut im Programmieren, bitte verzeih mir, dass du mir eine solche Frage gestellt hast.
Vielleicht, wenn Sie irgendwo eine Druckanweisung hatten? – betseyb
@ betseyb..Ich denke, ich habe die print-Anweisung in der kthSmallest() -Methode .. :) –