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

与えられた二分木で最大の独立集合(LIS)のサイズを見つけるためのC++プログラム


これは、与えられた二分木で最大の独立集合(LIS)のサイズを見つけるためのC++プログラムです。

アルゴリズム

Begin.
   Create a structure n to declare data d, a left child pointer l and a right child pointer r.
   Call a function max() to return maximum between two integers. Create a function LIS() to return the
   size of the largest independent set in a given binary tree.
   Calculate size excluding the current node
   int size_excl = LIS(root->l) + LIS(root->r)
   Calculate size including the current node
   int size_incl = 1;
   if (root->l)
      size_incl += LIS(root->l->l) + LIS(root->l->r)
   if (root->right)
      size_incl += LIS(root->r->l) + LIS(root->r->r)
      Return the maximum of two sizes
      Create a function to create newnode.
End.

サンプルコード

#include <iostream>
using namespace std;
struct n {
   int d;
   int lis;
   struct n *l, *r;
};
int max(int x, int y) {
   return (x > y) ? x : y;
}
int LIS(struct n *root) {
   if (root == NULL)
      return 0;
   if (root->lis)
      return root->lis;
   if (root->l == NULL && root->r == NULL)
      return (root->lis = 1);
      int lis_excl = LIS(root->l) + LIS(root->r);
      int lis_incl = 1;
   if (root->l)
      lis_incl += LIS(root->l->l) + LIS(root->l->r);
   if (root->r)
      lis_incl += LIS(root->r->l) + LIS(root->r->r);
      root->lis = max(lis_incl, lis_excl);
      return root->lis;
}
struct n* newnode(int d) {
   struct n* t = (struct n *) malloc(sizeof(struct n));
   t->d = d;
   t->l = t->r = NULL;
   t->lis = 0;
   return t;
}
int main() {
   struct n *root = newnode(30);
   root->l= newnode(20);
   root->l->l = newnode(10);
   root->l->r = newnode(7);
   root->l->r->l = newnode(9);
   root->l->r->r = newnode(6);
   root->r = newnode(50);
   root->r->r = newnode(26);
   cout<<"Size of the Largest Independent Set is "<< LIS(root);
   return 0;
}

出力

Size of the Largest Independent Set is 5

  1. C++で与えられた完全な二分木のすべてのノードの合計を見つけます

    完全な二分木のレベル数を表す正の整数Lがあるとします。この完全な二分木のリーフノードには、1からnまでの番号が付けられています。ここで、nはリーフノードの数です。親ノードは子の合計です。私たちの仕事は、この完璧な二分木のすべてのノードの合計を出力するプログラムを書くことです。したがって、ツリーが以下のようになっている場合- したがって、合計は30です。 よく見ると、すべてのノードの合計を見つける必要があります。リーフノードは1からnまでの値を保持しているため、式n(n + 1)/2を使用してリーフノードの合計を取得できます。これは完全な二分木であるため、各レベルの合計は同じになります

  2. Pythonの特定の二分木でBSTの最大合計値を見つけるプログラム

    二分木が提供されていると仮定します。そのサブツリーに二分探索木(BST)が存在するかどうかを調べ、最大のBSTの合計を見つける必要があります。合計を求めるために、そのBSTの各ノードの値を加算します。合計値を出力として返します。 したがって、入力が次のような場合 その場合、出力は12になります。 与えられた二分木のBSTは-です ノードの合計=12。 これを解決するには、次の手順に従います- c:=0 m:=null 値:=0 関数recurse()を定義します。これはノードを取ります ノードがnullでない場合、 left_val:=recurse(ノード