二分探索木の最小値を見つけるためのC++プログラム
二分探索木の最小値を見つけるプログラムです。
アルゴリズム
Begin Declare nd as a structure. Declare d to the integer datatype. Declare pointer lt to the structure nd type. Declare pointer lt to the structure nd type. Declare function new_nd() to the structure nd type. Declare d to the integer datatype. Pass them as a parameter. Declare pointer nd to the structure nd type. Initialize nd = (struct nd*) malloc(sizeof(struct nd)). nd->d = d. nd->lt = NULL. nd->rt = NULL. return(nd). End Begin Declare function add_node() to the structure nd type. Declare pointer nd to the structure nd type. Declare d to the integer datatype. Pass them as a parameter. if (nd == NULL) then return(new_nd(d)). else if (d <= nd->d) then nd->lt = add_node(nd->lt, d). else nd->rt = add_node(nd->rt, d). return nd. End Begin Declare minimum_val() function to the integer datatype. Declare pointer nd to the structure nd type. Pass it as a parameter. Declare pointer cur to the structure nd type. Initialize cur = nd. while (cur->lt != NULL) do cur = cur->lt. return(cur->d). Declare pointer root to the structure nd type. Initialize root = NULL. root = add_node(root, 54). add_node(root, 32). add_node(root, 25). add_node(root, 45). add_node(root, 65). add_node(root, 75). Print "The Minimum value of the given binary search tree is: ". Print the minimum value of binary tree. getchar(). End.
例
#include <bits/stdc++.h>
using namespace std;
struct nd {
int d;
struct nd* lt;
struct nd* rt;
};
struct nd* new_nd(int d) {
struct nd* nd = (struct nd*)
malloc(sizeof(struct nd));
nd->d = d;
nd->lt = NULL;
nd->rt = NULL;
return(nd);
}
struct nd* add_node(struct nd* nd, int d) {
if (nd == NULL)
return(new_nd(d));
else {
if (d <= nd->d)
nd->lt = add_node(nd->lt, d);
else
nd->rt = add_node(nd->rt, d);
return nd;
}
}
int minimum_val(struct nd* nd) {
struct nd* cur = nd;
while (cur->lt != NULL) {
cur = cur->lt;
}
return(cur->d);
}
int main() {
struct nd* root = NULL;
root = add_node(root, 54);
add_node(root, 32);
add_node(root, 25);
add_node(root, 45);
add_node(root, 65);
add_node(root, 75);
cout << "The Minimum value of the given binary search tree is: " << minimum_val(root);
getchar();
return 0;
} 出力
The Minimum value of the given binary search tree is: 25
-
C++の二分探索木で最小値のノードを見つけます
1つの二分探索木があるとします。二分探索木で最小要素を見つける必要があります。したがって、BSTが以下のような場合- 最小要素は1になります。 左のサブツリーは常に小さい要素を保持していることがわかっています。したがって、左がnullになるまで左のサブツリーを何度もトラバースすると、最小の要素を見つけることができます。 例 #include<iostream> using namespace std; class node{ public: node *left;
-
C ++プログラムでの二分探索?
二分探索は、半区間探索、対数探索、または二分探索とも呼ばれ、ソートされた配列内のターゲット値の位置を見つける検索アルゴリズムです。二分探索は、ターゲット値を配列の中央の要素と比較します。それらが等しくない場合、ターゲットが存在できない半分が削除され、残りの半分で検索が続行され、再び中央の要素がターゲット値と比較され、ターゲット値が見つかるまでこれが繰り返されます。残りの半分が空の状態で検索が終了した場合、ターゲットは配列に含まれていません。アイデアは単純ですが、バイナリ検索を正しく実装するには、特に配列の値が範囲内の整数のすべてではない場合、終了条件と中間点の計算に関する微妙な点に注意する必要