order in data structure code example
Example 1: preorder traversal
#include <iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree(){
int d;
cin>>d;
if(d==-1){
return NULL;
}
node * root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
void printIn(node*root){
if(root==NULL){
return;
}
printIn(root->left);
cout<<root->data<<" ";
printIn(root->right);
}
int main(){
node* root = buildTree();
printIn(root);
return 0;
}
Example 2: sorting in data structure
A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.