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

与えられた二分木がAVL木であるかどうかをチェックするC++プログラム


AVLツリーは自己平衡二分探索木であり、左右のサブツリーの高さの差がすべてのノードで複数になることはありません。

これは、特定のバイナリツリーがAVLツリーであるかどうかを確認するためのC++プログラムです。

アルゴリズム

Begin
function AVL() returns true if the given tree is AVL otherwise false.
   if(root == NULL)
      return 1
   leftheight = height(root->left)
   rightheight = height(root->right)
   if(abs(leftheight-rightheight) <= 1 && AVL(root->left) && AVL(root->right))
      return 1
   return 0
End

#include <bits/stdc++.h>
using namespace std;
class nod { //node declaration
   public:
   int data;
   nod* l;
   nod* r;
};
nod* newNod(int d) { //creation of new node
   nod* Nod = new nod();
   Nod->data = d;
   Nod->l = NULL;
   Nod->r = NULL;
   return(Nod);
}
int max(int x, int y) { //return maximum between two values
   return (x >= y)? x: y;
}
int height(nod* node) { //get the height means the number of nodes along the longest path from the root
node down to the farthest leaf node of the tree. 
   if(node == NULL)
      return 0;
   return 1 + max(height(node->l), height(node->r));
}
bool AVL(nod *root) {
   int lh;
   int rh;
   if(root == NULL)
      return 1;
   lh = height(root->l); // left height
   rh = height(root->r); // right height
   if(abs(lh-rh) <= 1 && AVL(root->l) && AVL(root->r)) return 1;
   return 0;
}
int main() {
   //take the nodes of the tree as input
   nod *root = newNod(7);
   root->l = newNod(6);
   root->r = newNod(12);
   root->l->l = newNod(4);
   root->l->r = newNod(5);
   root->r->r = newNod(13);
   if(AVL(root))
      cout << "The Tree is AVL Tree"<<endl;
   else
      cout << "The Tree is not AVL Tree "<<endl;
   nod *root1 = newNod(7);
   root1->l = newNod(6);
   root1->r = newNod(12);
   root1->l->l = newNod(4);
   root1->l->r = newNod(5);
   root1->r->r = newNod(13);
   root1->r->r->r = newNod(26);
   if(AVL(root1))
      cout << "The Tree is AVL Tree"<<endl;
   else
      cout << "The Tree is not AVL Tree "<<endl;
   return 0;
}

出力

The Tree is AVL Tree
The Tree is not AVL Tree

  1. バイナリツリーがC++でレベルごとにソートされているかどうかを確認します

    ここでは、二分木がレベルごとにソートされているかどうかを確認する方法を説明します。レベルごとにソートされた二分木は次のようになります- 各レベルでは、ノードは左から右に並べ替えられ、各レイヤーには前のレベルよりも高い値が含まれています。 レベル順序トラバーサルを実行することでこの問題を解決し、現在のレベルの最小要素と最大要素を追跡できます。別の変数prev_maxを使用して、前のレベルの最大値を保持します。次に、現在のレベルの最小値と前のレベルの最大値prev_maxを比較します。 min値がprev_maxより大きい場合、ツリーは現在のレベルまでレベルごとに並べ替えられます。次に、

  2. AVLツリーを実装するためのC++プログラム

    AVLツリーは自己平衡二分探索木であり、左右のサブツリーの高さの差がすべてのノードで複数になることはありません。 ツリーの回転は、AVLツリーの要素の順序を妨げることなく構造を変更する操作です。ツリー内で1つのノードを上に移動し、1つのノードを下に移動します。これは、ツリーの形状を変更したり、小さいサブツリーを下に移動したり、大きいサブツリーを上に移動したりして高さを低くしたりするために使用され、多くのツリー操作のパフォーマンスが向上します。回転の方向は、木のノードが移動する側に依存しますが、他の人は、どの子がルートの場所をとるかに依存すると言います。これは、AVLツリーを実装するためのC+