Javaプログラムを作成して、BSTのk番目に小さい要素を見つけようとしています。JavaプログラムでBSTのk番目に小さい要素を見つける
私はスタックオーバーフローに関するこの質問の他の記事を読んで、解決策を見つけましたが、私のコードで何が問題であるのか理解できません。 誰でも私のプログラムが何も印刷していない理由を教えてください。次のように
//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);
}
}
そして、私のノードクラスがある:それは印刷されません
//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;
}
}
anything.Thatが問題です。 私はプログラミングがうまくいきませんので、ここでそのような質問をしてくださったことをご容赦ください。
もしかしたらどこかにプリント文があったら? – betseyb
@ betseyb ..私はkthSmallest()メソッドでprintステートメントを持っていると思います。:) –