layman_coder
BAN USER#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<queue>
struct tree
{
int data;
struct tree * left;
struct tree *right;
};
struct tree * create(int num)
{
struct tree * temp = (struct tree *)malloc(sizeof(struct tree));
temp->data=num;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(struct tree **root,int num)
{
if(*root ==NULL)
{
*root=create(num);
}
else
{
if(num < (*root)->data)
insert(&(*root)->left,num);
else
insert(&(*root)->right,num);
}
}
struct node
{
int data;
struct node *next;
};
struct node * createNode(int num)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
if(temp)
{
temp->data = num;
temp->next = NULL;
return temp;
}
else
return NULL;
}
void addToList(struct node **head, int num)
{
if(*head == NULL)
{
*head = createNode(num);
}
else
{
struct node *temp = *head;
while(temp->next!=NULL)
temp = temp->next;
temp->next = createNode(num);
}
}
void printList(struct node *head)
{
while(head)
{
if(head->next)
printf("%3d->",head->data);
else
printf("%3d",head->data);
head = head->next;
}
}
void freeList(struct node **head)
{
struct node *cur = *head;
struct node *nxt = NULL;
while(cur !=NULL)
{
nxt = cur->next;
free(cur);
cur=nxt;
}
*head = NULL;
}
int MAXM(int a, int b)
{
return a >b ? a : b;
}
int heightOfTree(struct tree *root)
{
if(!root)
return 0;
else
return (1 + MAXM(heightOfTree(root->left), heightOfTree(root->right)));
}
void printEachLevel(struct tree * root, int level, struct node **head)
{
if(root==NULL)
return;
if(level == 1)
{
addToList(head,root->data);
}
else
{
printEachLevel(root->left, level-1,head);
printEachLevel(root->right, level-1,head);
}
}
void printLevelWise(struct tree * root)
{
int height = heightOfTree(root);
struct node *head = NULL;
for(int i = 1; i<=height; i++)
{
printEachLevel(root,i,&head);
printf("\n");
printList(head);
freeList(&head);
}
}
int main()
{
struct tree *root = NULL;
insert(&root,10);
insert(&root,6);
insert(&root,17);
insert(&root,4);
insert(&root,14);
insert(&root,19);
printLevelWise(root);
getch();
return 0;
}
- layman_coder February 28, 2015I used recursion to find the max sum
int getsum(int *a,int size,int high, int low,int *h,int *l)
{
//base case
while(low<high-1)
//find the least value of low
if((a[high]-a[low] ) >0)
{
sum= (a[high]-a[low])> get(a,size,high-1,low,h,l) ? (a[high]-a[low]) : get(a,size,high-1,low,h,l)
return sum;
}
}
int main()
{
int a[size],sum=0,l=0,h=0;
sum=getsum(a,size,size-1,0,&h,&l);
if(h <size-2)
sum=sum+getsum(a,size,size-1,h+1,&h,&l);
printf("Answer =%d",sum);
}
This can be solved using backtracking.
- layman_coder April 10, 20151. sort the string based on number of occurrences. e.g. d(3),a(2),b(2),c(1)
2. start from the most frequent char, and decrease the count to -1.
3. now do the same next most frequent char and keep updating the count.
4. if two characters collide, backtrack and repeat the same with next most frequent char.