Sunday, February 20, 2011

WAP to Convert Binary Tree into Singly Linked List

#include
#include

#define max(a,b) (a) > (b) ? (a) : (b)

/*Data structures*/
typedef struct TreeNode
{
struct TreeNode *left, *right;
int data;
}TreeNode;

typedef TreeNode * Tree;

typedef struct ListNode
{
struct ListNode *next;
int data;

}ListNode;

typedef ListNode *List;

/*End of data structures*/

/*
*Function which collapses all the nodes at a level in a binary tree to one Listnode
*/
void BinTreeToLinkedList(Tree t, ListNode *parent)
{
if(t == NULL)
return;

ListNode *node = parent->next;

if(node == NULL)
{
node = calloc(sizeof(ListNode), 1);
parent->next = node;
}

node->data += t->data;

BinTreeToLinkedList(t->left, node);
BinTreeToLinkedList(t->right, node);
}


/*Utilities*/

inline TreeNode * makeTreeNode(int data)
{
TreeNode *n = calloc(sizeof(TreeNode), 1);
n->data = data;

return n;
}

inline void printList(List l)
{
while(l)
{
printf("%d ", l->data);
l = l->next;
}
printf("\n");
}

int main()
{
/*level 0*/
Tree t = makeTreeNode(10);

/*level 1*/
t->left = makeTreeNode(20);
t->right = makeTreeNode(30);


/*level 2*/
t->left->left = makeTreeNode(40);
t->left->right = makeTreeNode(70);
t->right->left = makeTreeNode(50);
t->right->right = makeTreeNode(60);

/*level 3*/
t->left->right->left = makeTreeNode(70);
t->right->right->left = makeTreeNode(60);
t->right->right->right = makeTreeNode(160);

/*Empty List head*/
ListNode head = {NULL, 0};

/*Convert tree to list*/
BinTreeToLinkedList(t, &head);

/*print list*/
printList(head.next);


return 0;
}

Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/DWMmM

WAP to Delete A kth Node fromThe End in Linked List

#include
#include

/* Link list node */
struct node
{
int data;
struct node* next;
};

/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct node *head, int n)
{
struct node *main_ptr = head;
struct node *ref_ptr = head;
struct node *prev=NULL;
struct node *temp=NULL;

int count = 0;
if(head != NULL)
{
while( count < n )
{
if(ref_ptr == NULL)
{
printf("%d is greater than the no. of "
"nodes in list", n);
return;
}
ref_ptr = ref_ptr->next;
count++;
} /* End of while*/

while(ref_ptr != NULL)
{ prev=main_ptr;
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
temp=main_ptr;
prev->next=temp->next;
//main_ptr=head;
printf("Node no. %d from last is %d ",
n, temp->data);

free(temp);
}
}

void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

void print(struct node *current)
{
while(current!=NULL)
{
printf(" %d --> ", current->data);
current=current->next;

}

}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 5);
push(&head, 20);

printNthFromLast(head, 3);

print(head);

getchar();
}

Run Length Encoding of String

/*
You have a character array containing upper and lower case letters of the English alphabet. Do a run-length encoding of the array.
e.g. if the array is aaaBBAcc, its run-length encoding is a3B2Ac2.
Function prototype is

char * runLengthEncode(char * A)

Note: Make sure you take care of critical cases like when the count of a character exceeds 9

*/


#include
#include
#include
#define MAX_RLEN 50

/* Returns the Run Length Encoded string for the
source string src */
char *encode(char *src)
{
int rLen;
char count[MAX_RLEN];
int len = strlen(src);
int p=0;

/* If all characters in the source string are different,
then size of destination string would be twice of input string.
For example if the src is "abcd", then dest would be "a1b1c1"
For other inputs, size would be less than twice. */
char *dest = (char *)malloc(sizeof(char)*(len*2 + 1));

int i, j = 0, k;

/* traverse the input string one by one */
for(i = 0; i < len; i++)
{

/* Copy the first occurrence of the new character */
dest[j++] = src[i];

/* Count the number of occurrences of the new character */
rLen = 1;
while(i + 1 < len && src[i] == src[i+1])
{
rLen++;
i++;
}

/* Store rLen in a character array count[] */
sprintf(count, "%d", rLen);//it will resolve problem when count>9

//count[p]=((char)rLen);//it will create problem when count>9
p++;

/* Copy the count[] to destination */
for(k = 0; *(count+k); k++, j++)
{
dest[j] = count[k];
}
}

/*terminate the destination string */
dest[j] = '\0';
return dest;
}

/*driver program to test above function */
int main()
{
char str[] = "aaaaaaaaaaaaaaabbbbbcd";
char *res = encode(str);
printf("%s", res);
getchar();
}

Run Length Encoding opf String

/*
You have a character array containing upper and lower case letters of the English alphabet. Do a run-length encoding of the array.
e.g. if the array is aaaBBAcc, its run-length encoding is a3B2Ac2.
Function prototype is

char * runLengthEncode(char * A)

Note: Make sure you take care of critical cases like when the count of a character exceeds 9

*/


#include
#include
#include
#define MAX_RLEN 50

/* Returns the Run Length Encoded string for the
source string src */
char *encode(char *src)
{
int rLen;
char count[MAX_RLEN];
int len = strlen(src);
int p=0;

/* If all characters in the source string are different,
then size of destination string would be twice of input string.
For example if the src is "abcd", then dest would be "a1b1c1"
For other inputs, size would be less than twice. */
char *dest = (char *)malloc(sizeof(char)*(len*2 + 1));

int i, j = 0, k;

/* traverse the input string one by one */
for(i = 0; i < len; i++)
{

/* Copy the first occurrence of the new character */
dest[j++] = src[i];

/* Count the number of occurrences of the new character */
rLen = 1;
while(i + 1 < len && src[i] == src[i+1])
{
rLen++;
i++;
}

/* Store rLen in a character array count[] */
//sprintf(count, "%d", rLen);

count[p]=((char)rLen);
p++;

/* Copy the count[] to destination */
for(k = 0; *(count+k); k++, j++)
{
dest[j] = count[k];
}
}

/*terminate the destination string */
dest[j] = '\0';
return dest;
}

/*driver program to test above function */
int main()
{
char str[] = "aaaaaaaaaaaaaaabbbbbcd";
char *res = encode(str);
printf("%s", res);
getchar();
}

WAP to Do Level Order Sum of Binary Tree

#include
#include

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/*Function protoypes*/
int printGivenLevel(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);

/* Function to print level order traversal a tree*/
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for(i=1; i<=h; i++)
printf(" %d \t ",printGivenLevel(root, i));
}

/* Print nodes at a given level */
int printGivenLevel(struct node* root, int level)
{
if(root == NULL)
return;
if(level == 1)
{
return root->data;
}
else if (level > 1)
{
return (printGivenLevel(root->left, level-1)+ printGivenLevel(root->right, level-1));
}
}

/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);

/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(4);
root->right->right = newNode(5);

printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);

printf("\t height=%d",height(root));

getchar();
return 0;
}

WAP to FindOut the Vrtical Sum of nodes values in BInary Tree

#include
#include

/* A binary tree node has data, pointer to left child
and a pointer to right child */

struct node
{
int data;
struct node* left;
struct node* right;
};

int verticalsum[]={0,0,0,0,0,0,0};
//verticalsum[-1]={0};
//verticalsum[-2]={0};

int size=sizeof(verticalsum)/sizeof(int);

void vertcal_sum(struct node *root, int level)
{
if(root!=NULL)
{
verticalsum[level]+=root->data;
vertcal_sum(root->left,level-1);
vertcal_sum(root->right,level+1);
}
}

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int maxDepth(struct node* node)
{
if (node==NULL)
return -1;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);

/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}

/* Driver program to test above functions*/
int main()
{ int i=0;
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
//root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);

int depth=maxDepth(root);
printf("Level Order traversal of binary tree is \n");
vertcal_sum(root,depth);


for(i=0;i printf(" %d ", verticalsum[i]);

getchar();
return 0;
}

TC O(n)
Sc O(n) to show the output using array its not auxiliary space
Run Here https://ideone.com/PZeo3


Another Solution is Using HashMap , Its Efficient The Privious One as we are not wasting space . An Anon Commented on This Post, so i am posting it here .

import java.util.HashMap;
public class TreeApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
tree t=new tree();
t.insert('C');
t.insert('E');
t.insert('A');
t.insert('B');
t.insert('D');
t.insert('F');
t.display();
t.printVertically(t.getRoot(), 0);
t.displayHash();
}
}
class tree{
private treeNode root;
private HashMap<Integer,Integer> h;
public treeNode getRoot(){
return root;
}
void insert(char ch){
treeNode parent;
treeNode current=root;
treeNode newNode= new treeNode();
newNode.data=ch;
while(true){
if(root==null){
root=newNode;
return;
}
else{
parent=current;
if(ch<current.data){
current=current.leftChild;
if(current==null){
parent.leftChild=newNode;
break;
}
}
else{
current=current.rightChild;
if(current==null){
parent.rightChild=newNode;
break;
}
}
}
}
}
void display(){
treeNode curr=root;
h=new HashMap<Integer,Integer>();
inorderTraversal(curr);
}
private void inorderTraversal(treeNode curr) {
// TODO Auto-generated method stub
if(curr!=null){
inorderTraversal(curr.leftChild);
System.out.println("data->"+curr.data);
inorderTraversal(curr.rightChild);
}
}
public void printVertically(treeNode root,int level){
if(root!=null){
printVertically(root.leftChild,level-1);
int lvalue;
if(h.get(level)==null){
lvalue=0;
}
else{
lvalue=h.get(level);
}
h.put(level, lvalue+root.data);
printVertically(root.rightChild,level+1);
}
}
public void displayHash(){
for(Integer i:h.keySet())
System.out.println("Hash key->"+i+" Value"+h.get(i));
}
class treeNode{
char data;
treeNode leftChild;
treeNode rightChild;
}
}
TC O(N)
SC O(N)

WAP to Iniatlize GrandParent Binary Tree

/*

You are given a special kind of binary tree, in which there is another attribute, “grandparent”, which is a pointer to the grandparent of a node. The tree structure is thus,
struct Node
{
int val;
node * left;
node * right;
node * grandparent;
};
root
/ \






In the tree given to you, the grandparent attribute for each node is initialized to NULL. Write a function to initialize the grandparent attribute.
Note: The value of the “grandparent” attribute for the root and first level nodes will be NULL.
Function Prototype,

void initializeGrandParent(node * root)
3. Convert a binary tree into a doubly-linked list so that the order of the elements in the list should be equivalent to a zig-zag traversal of the tree

*/




#include
#include


struct Node
{
struct Node *left;
struct Node *right;
struct Node *grandparent;
int data;

};

void SetGrandParent(struct Node *);


int isLeaf(struct Node *n)
{
return (n->left==NULL && n->right==NULL);

}

int isAtHeightLEOne(struct Node *n)
{

return ((n==NULL) || ((n->left==NULL) ||isLeaf(n->left)) && ((n->right==NULL) || isLeaf(n->right)) );

}

void setGrand(struct Node *p, struct Node *root)
{
if(p->left)
p->left->grandparent=root;

if(p->right)
p->right->grandparent=root;

}

void SetGrandParent(struct Node *t)
{
if(isAtHeightLEOne(t))
return;

struct Node *p=t->left;

if(p)
{
setGrand(p,t);
SetGrandParent(p);

}
p=t->right;
if(p)
{

setGrand(p,t);
SetGrandParent(p);

}



}

struct Node* newNode(int data)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->grandparent=NULL;

return(node);
}

/* Driver program to test above functions*/
int main()
{

/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 8
*/
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(8);



SetGrandParent(root);


printf(" %d %d %d ",root->left->left->grandparent->data,root->left->right->grandparent->data,root->right->left->grandparent->data);



getchar();
return 0;
}

WAP to Sort an array of 0s, 1s and 2s

Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last.

Example
Input = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
Output = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}

Algorithm

The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.

The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections:

1. a[1..Lo-1] zeroes (red)
2. a[Lo..Mid-] ones (white)
3. a[Mid..Hi] unknown
4. a[Hi+1..N] twos (blue)

The unknown region is shrunk while maintaining these conditions

1. Lo := 1; Mid := 1; Hi := N;
2. while Mid <= Hi do
1. Invariant: a[1..Lo-1]=0 and a[Lo..Mid-1]=1 and a[Hi+1..N]=2; a[Mid..Hi] are unknown.
2. case a[Mid] in
* 0: swap a[Lo] and a[Mid]; Lo++; Mid++
* 1: Mid++
* 2: swap a[Mid] and a[Hi]; Hi–

— Dutch National Flag Algorithm, or 3-way Partitioning —

Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:

|
0 0 0 1 1 1 ? ? ? ? 2 2 2
^ ^ ^
| | |
Lo Mid Hi

Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue.
Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++

0 0 0 0 1 1 1 ? ? ? 2 2 2
^ ^ ^
| | |
Lo Mid Hi

Case (1) a[Mid] is white, Mid++

0 0 0 1 1 1 1 ? ? ? 2 2 2
^ ^ ^
| | |
Lo Mid Hi

Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–

0 0 0 1 1 1 ? ? ? 2 2 2 2
^ ^ ^
| | |
Lo Mid Hi

Continue until Mid>Hi.

program:

#include

/* Function to swap *a and *b */
void swap(int *a, int *b);

void sort012(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0;

while(mid <= hi)
{
switch(a[mid])
{
case 0:
swap(&a[lo++], &a[mid++]);
break;
case 1:
mid++;
break;
case 2:
swap(&a[mid], &a[hi--]);
break;
}
}
}

/* UTILITY FUNCTIONS */
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

/* Utility function to print array arr[] */
void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* driver program to test */
int main()
{
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int i;

sort012(arr, arr_size);

printf("array after segregation ");
printArray(arr, arr_size);

getchar();
return 0;
}

WAP to Segregate An Array of 0s,1s

#include

/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size-1;

while(left < right)
{
/* Increment left index while we see 0 at left */
while(arr[left] == 0 && left < right)
left++;

printf(" left=%d \n",left);

/* Decrement right index while we see 1 at right */
while(arr[right] == 1 && left < right)
right=right-1;

printf(" right=%d \n",right);
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right=right-1;
}
}
}

/* driver program to test */
int main()
{
int arr[] = {1,1, 1,0,0,0};
int arr_size = 6, i = 0;

segregate0and1(arr, arr_size);

printf("array after segregation ");
for(i = 0; i < 6; i++)
printf("%d ", arr[i]);

getchar();
return 0;
}

WAP to Find kth Maximum & Minimum in BST

#include
#include
#include


/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/* Helper function that allocates a new node
with the given data and NULL left and right
pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

/* Give a binary search tree and a number,
inserts a new node with the given number in
the correct place in the tree. Returns the new
root pointer which the caller should then use
(the standard trick to avoid using reference
parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);

/* return the (unchanged) node pointer */
return node;
}
}


int kthMax(struct node* t, int *k) {

if(t == NULL)
return INT_MIN;

int x = kthMax(t->right, k);

if(x != INT_MIN) return x;

(*k)--;
if(*k == 0) return t->data;

return kthMax(t->left, k);
}


int kthMin(struct node* t, int *k) {

if(t == NULL)
return INT_MAX;

int x = kthMin(t->left, k);

if(x != INT_MAX) return x;

(*k)--;
if(*k == 0) return t->data;

return kthMin(t->right, k);
}


/* Driver program to test sameTree function*/
int main()
{
struct node* root = NULL;
root = insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);

int n=5,m=5;
printf("Given Min in BST is %d \t Max is=%d", kthMin(root,&n),kthMax(root,&m));
getchar();
return 0;
}

Java program to doing the Same

import java.util.Random;
import java.util.Stack;


public class BinaryTree {

private static int N = 7;
private static Node root = null;
public static int K = 3;
private static int INDEX = 0;
public static void main(String [] args) {
root = buildBST(root);
System.out.println("Printing inorder: ");
inorder(root);
System.out.println();
System.out.println("K value: " + K);
findKthSmallestIterative(root);
findKthSmallesRecursive(root);
}

public static void findKthSmallesRecursive(Node node) {
Stack stack = new Stack();
int i=1;
while (!stack.isEmpty() || node != null) {

if (node == null) {
node = stack.pop();
if (i == K) {
System.out.println("Kth Node :" + node.data);
}
++i;
node = node.right;
}
if (node != null) {
stack.push(node);
node = node.left;
}
}
}

public static void findKthSmallestIterative(Node node) {
if (node == null) {
System.out.println("Tree is empty!!");
return;
}
if (node.left != null) {
findKthSmallestIterative(node.left);
}

++INDEX;
if (K == INDEX) {
System.out.println("Kth Smallest Node Value: " + node.data);
return;
}

if (node.right != null) {
findKthSmallestIterative(node.right);
}
}

public static void inorder(Node node) {
if (node == null) { return ; }

if (node.left != null) {
inorder(node.left);
}
System.out.print(node.data + " ");
if (node.right != null) {
inorder(node.right);
}
}

public static Node buildBST(Node node) {
Random rand = new Random();

for (int i=0; i int value = rand.nextInt(99) + 1;
node = buildBST(node, value);
System.out.print(value + " ");
}
System.out.println();

return node;
}

private static Node buildBST(Node node, int data) {
if (node == null) { return new Node(data); }

if (data <= node.data) {
node.left = buildBST(node.left, data);
} else {
node.right = buildBST(node.right, data);
}
return node;
}
}

class Node {
Node left;
Node right;
int data;

Node(int data) {
this.data = data;
left = null;
right = null;
}
}


TC O(n)
SC O(1)
Run Here https://ideone.com/TeT4E