6-LABARATORIYA MASHG’ULOTI
Mavzu: Daraxtsimon ma’lumotlar tuzilmasini tadqiq qilish ,binar daraxt bo’yicha qidiruv funksiyasi.
Dastur kodi
#include #include using namespace std; class node{
public: int info; node *left; node *right;
};
int k=0,Flag=1;
int height(node *tree){ int h1,h2;
if (tree==NULL) return (-1); else {
h1 = height(tree->left); h2 = height(tree->right);
if (h1>h2) return (1 + h1); else return (1 + h2);
}
}
void vizual(node *tree,int l)
{ int i; if(tree!=NULL) {
vizual(tree->right,l+1);
for (i=1; i<=l; i++) cout<<" "; cout<info< vizual(tree->left,l+1);
}
}
int AVLtree (node *tree){ int t;
if (tree!=NULL){
t = height (tree->left) - height (tree->right); if ((t<-1) || (t>1)) { Flag = 0; return Flag; } AVLtree (tree->left); AVLtree (tree->right);
}
}
int GetFlag(){return Flag;} int main()
{ int n,key,s; node *tree=NULL,*next=NULL; cout<<"n="; cin>>n; int arr[n];
for(int i=0; i node *p=new node; node *last=new node; cin>>s;
p->info=s;
>left=NULL; p->right=NULL;
if(i==0){tree=p; next=tree; continue; } next=tree;
while(1)
{ last=next;
if(p->infoinfo)next=next->left; else next=next->right; if(next==NULL)break; }
if(p->infoinfo)last->left=p; else last->right=p;}
cout< cout<<"\nbinar daraxt:\n"; vizual(tree,0); AVLtree(tree);
if(GetFlag()) cout<<"ha,muvozanatlangan daraxt"; else cout<<"yo’q, muvozanatlanmagan daraxt";cout<
getch();
}
Dastur natijasi
6-topshiriq.
Daraxt tugunlari haqiqiy sonlar bo’sin . Yozuvi berilgan kalit qiymatidan kata bo’lgan daraxt tugunlarini o’chiruvchi dastur tuzing.
#include
using namespace std;
struct Node {
double value;
Node* left;
Node* right;
};
Node* createNode(double value) {
Node* node = new Node;
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
Node* insertNode(Node* root, double value) {
if (root == NULL) {
return createNode(value);
}
if (value < root->value) {
root->left = insertNode(root->left, value);
} else {
root->right = insertNode(root->right, value);
}
return root;
}
Node* deleteNode(Node* root, double x) {
if (root == NULL) {
return NULL;
}
if (root->value > x) {
root->left = deleteNode(root->left, x);
root->right = deleteNode(root->right, x);
} else {
Node* left = root->left;
Node* right = root->right;
delete root;
root = NULL;
root = insertNode(root, right);
root = insertNode(root, left);
}
return root;
}
void printTree(Node* root) {
if (root == NULL) {
return;
}
printTree(root->left);
cout << root->value << " ";
printTree(root->right);
}
int main() {
Node* root = NULL;
root = insertNode(root, 5.0);
root = insertNode(root, 3.0);
root = insertNode(root, 7.0);
root = insertNode(root, 2.0);
root = insertNode(root, 4.0);
root = insertNode(root, 6.0);
root = insertNode(root, 8.0);
double x = 5.0;
root = deleteNode(root, x);
printTree(root);
return 0;
}
Bajaruvchi: Jumaboyev Eldor
Do'stlaringiz bilan baham: |