C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

二分探索アプローチを使用して配列の最小要素を見つけるC++プログラム


これは、線形探索アプローチを使用して配列の最小要素を見つけるためのC++プログラムです。このプログラムの時間計算量はO(log(n))です。

アルゴリズム

Begin
   Construct binary search tree for the given unsorted data array.
   To find out the minimum element move the pointer to the leftmost child node.
   Print this value as minimum value among the given data.
End

サンプルコード

#include<iostream>
using namespace std;
struct node {
   int d;
   node *left;
   node *right;
};
node* CreateNode(int d) {
   node *newnode = new node;
   newnode->d = d;
   newnode->left = NULL;
   newnode->right = NULL;
   return newnode;
}
node* InsertIntoTree(node* root, int d) {
   node *temp = CreateNode(d);
   node *t = new node;
   t = root;
   if(root == NULL)
      root = temp;
   else{
      while(t != NULL) {
         if(t->d < d) {
            if(t->right == NULL) {
               // If current node is NULL then insert the node.
               t->right = temp;
               break;
            }
            // Shift pointer to the left.
            t = t->right;
         }
         else if(t->d > d) {
            if(t->left == NULL) {
               t->left = temp;
               break;
            }
            t = t->left;
         }
      }
   }
   return root;
}
int main() {
   int n, i, a[10]={86, 63, 95, 6, 7, 67, 52, 26, 45, 98};
   node *root = new node;
   root = NULL;
   cout<<"\nData set:\n";
   for(i = 0; i < 10; i++) {
      cout<<a[i]<<" ";
      root = InsertIntoTree(root, a[i]);
   }
   cout<<"\n\nThe minimum element of the given data set is ";
   i = 0;
   while(root->left != NULL) {
      i++;
      root = root->left;
   }
   cout<<root->d<<" which found at "<<i<<" depth from the root.";
   return 0;
}

出力

Data set:
86 63 95 6 7 67 52 26 45 98
The minimum element of the given data set is 6 which found at 2 depth from the root.

  1. C++のバイナリ検索ツリーで最も近い要素を検索します

    1つの二分探索木(BST)と別のターゲット値があるとします。その与えられたBSTで、ターゲットに最も近いk個の値を見つける必要があります。ここで、ターゲット値は浮動小数点数です。 kは常に有効であり、k≤合計ノードであると想定できます。 したがって、入力が次のような場合 target =3.714286、k =2の場合、出力は[4,3]になります。 これを解決するには、次の手順に従います- 関数pushSmaller()を定義します。これにより、ノード、スタックst、およびターゲットが取得されます。 ノードが存在しない場合は、-を実行します ノードの値が<ターゲッ

  2. C++の二分探索木で最小値のノードを見つけます

    1つの二分探索木があるとします。二分探索木で最小要素を見つける必要があります。したがって、BSTが以下のような場合- 最小要素は1になります。 左のサブツリーは常に小さい要素を保持していることがわかっています。したがって、左がnullになるまで左のサブツリーを何度もトラバースすると、最小の要素を見つけることができます。 例 #include<iostream> using namespace std; class node{    public:       node *left;