In: Computer Science
C++ AVL tree
My AVL tree function
void inorder(AVLNode* t)
{
if (t == NULL)
return;
inorder(t->left);
cout << t->data.cancer_rate << " ";
inorder(t->right);
}
void inorder()
{
inorder(root);
}
Will Print my cancer city rate Inorder
example)
3.1
5.8
19.8
My question is how can I add a decreasing index to this function
example)
3) 3.1
2)5.8
1)19.8
You can modify your inorder function slightly to achieve what you want. Please look two sets of examples below
Block 1 (Your Current State)
#include <bits/stdc++.h>
using namespace std;
struct Data{
double cancer_rate;
};
typedef struct node{
struct Data data;
struct node* left;
struct node* right;
}AVLNode;
void inorder(AVLNode* t){
if (t == NULL)
return;
inorder(t->left);
cout << t->data.cancer_rate <<endl;
inorder(t->right);
}
AVLNode* new_AVLNode(double cancer_rate){
AVLNode* root = new AVLNode;
root->left=NULL;
root->right=NULL;
root->data = {cancer_rate};
}
int main(int argc, char const *argv[])
{
AVLNode* root = new_AVLNode(5.8);
root->left = new_AVLNode(3.1);
root->right = new_AVLNode(19.8);
inorder(root);
}
Console Output for Block 1
3.1
5.8
19.8
Block 2 with required changes
#include <bits/stdc++.h>
using namespace std;
struct Data{
double cancer_rate;
};
typedef struct node{
struct Data data;
struct node* left;
struct node* right;
}AVLNode;
void inorder(AVLNode* t){
if (t == NULL)
return;
inorder(t->left);
cout << t->data.cancer_rate <<endl;
inorder(t->right);
}
//notice that we have passed counter by reference
void inorder_with_decrement_counter(AVLNode* t, int &counter){
if (t == NULL)
return;
inorder_with_decrement_counter(t->left, counter);
cout << (counter--)<<") "<<t->data.cancer_rate <<endl;
inorder_with_decrement_counter(t->right, counter);
}
AVLNode* new_AVLNode(double cancer_rate){
AVLNode* root = new AVLNode;
root->left=NULL;
root->right=NULL;
root->data = {cancer_rate};
}
int tree_size(AVLNode* t){
if(t==NULL)
return 0;
else
return 1+ tree_size(t->left)+tree_size(t->right);
}
int main(int argc, char const *argv[])
{
AVLNode* root = new_AVLNode(5.8);
root->left = new_AVLNode(3.1);
root->right = new_AVLNode(19.8);
cout<<"Normal inorder."<<endl;
inorder(root);
cout<<"Inorder with decrement counter."<<endl;
int size = tree_size(root);
inorder_with_decrement_counter(root, size);
}
Console Output for Block 2
Normal inorder.
3.1
5.8
19.8
Inorder with decrement counter.
3) 3.1
2) 5.8
1) 19.8
Let me know in comments if you have any doubts. Do leave a thumbs up if this was helpful.