私が今やろうとしていることは、私のバイナリ検索ツリー(BST)の繰り返し回数の最小値を見つけることです。私のBSTで最小のカウントを見つける方法
これは、値を挿入するときにBSTが正常であることを意味しますが、同じ値を2回取得すると、代わりにツリーが依存しない繰り返しカウントの値が増えます(したがって、最小値のためにちょうど左に行く)。
私は最小値を取得しようとしましたが、常に短くなります。最小を取得しようとしている機能は、ここでfindSmallest
public static void main(String[] args) {
int x = 0; //random number
Random rnum = new Random();
SBT sbt = new SBT();
for(int i = 0; i < 100; i++){
x = rnum.nextInt(20) + 1;
sbt.insert(x);
}
sbt.printLargestCount();
sbt.printSmallestCount();
sbt.FS();
sbt.deleteBoth();
System.out.println("Sum of the key values is: " + sbt.sumKeyValue());
System.out.println("Sum of the repeat counts is: " + sbt.sumReapeatCount());
sbt.inorder();
}
である私は今、ツリー内のすべてのノードを通過しようとしていると、現在の最小値と比較することしていた値を取得しようとしている機能です。 ノードrepeatCount
がその値より小さい場合、値が変更され、グローバルノードsmallestCount
が変更されます。
以下のグローバルを追加しました。
private BSTNode root;
private BSTNode largestCount;
private BSTNode smallestCount;
private int sumKeyVal;
public void FS(){
findSmallest(root, 0);
System.out.println("data is: " + smallestCount.data + " repeatCount is: " + smallestCount.repeatCount);
}
private void findSmallest(BSTNode r, int val){
if(r == null) return;
if(r == root)val = r.repeatCount;
if(r.repeatCount < val){
val = r.repeatCount;
smallestCount = r;
System.out.println(val);
}
if(r.right == null && r.left == null)
return;
else if(r.left != null)
findSmallest(r.left,val);
else if(r.right != null)
findSmallest(r.right,val);
}
private BSTNode insert(int x, BSTNode t){
if (t == null){
t = new BSTNode(x);
smallestCount = t;
}
else if (x < t.data)
t.left = insert(x, t.left);
else if (x > t.data)
t.right = insert(x, t.right);
else
t.height = max(height(t.left), height(t.right)) + 1;
return t;
}
private int height(BSTNode t) {
return t == null ? -1 : t.height;
}
// Function to max of left/right node
private int max(int lhs, int rhs) {
return lhs > rhs ? lhs : rhs;
}
ここで使用されるノードのクラスがある:
public class BSTNode {
BSTNode left, right;
int data;
int height;
int repeatCount;
/* Constructor */
public BSTNode(){
left = null;
right = null;
data = 0;
height = 0;
repeatCount = 0;
}
/* Constructor */
public BSTNode(int n){
left = null;
right = null;
data = n;
height = 0;
repeatCount = 0;
}
}