How to write a C Program to defined Node in C Programming Language ?
Solution:
/* Node is defined as : typedef struct node { int val; struct node* left; struct node* right; int ht; } node; */ int nht(node * root); int height (node * root); int bfactor (node * root); node * newnode(int val); node * insert(node * root, int val); node * balance (node * root); node * lr(node * root); node * rr ( node * root); node * newnode(int val) { node * temp = (node *) malloc(sizeof(node)); temp->val = val; temp->left = NULL; temp->right = NULL; temp->ht = 1; return temp; } int height(node * root) { if(root) return root->ht; else return 0; } int nht(node * root) { int x = height(root->right); int y = height(root->left); if (x>y) return x+1; else return y+1; } int bfactor(node * root) { return height(root->left)-height(root->right); } node * rr ( node * root ) { node * x; x = root->left; root->left = x->right; x->right = root; root->ht = nht(root); x->ht = nht(x); return x; } node * lr ( node * root ) { node * x; x = root->right; root->right = x->left; x->left = root; root->ht = nht(root); x->ht = nht(x); return x; } node * insert (node * root, int val) { if (!root) return newnode(val); else if (root->val < val) { root->right= insert (root->right, val); } else { root->left= insert (root->left, val); } root->ht = nht(root); int bal = bfactor(root); if(bal>1) { if (bfactor(root->left)>=0) return rr(root); else { root->left = lr(root->left); return rr (root); } } if(bal<-1) { if (bfactor(root->right)<=0) return lr(root); else { root->right = rr(root->right); return lr (root); } } return root; }