Sunday, August 28, 2011

morris inorder traversal

or stackless traversal

this is elegant algorithm from Morris for stackless inorder

void MorrisTraversal(struct tNode *root)
{
struct tNode *current,*pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
printf(" %d ", current->data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predecessor */
if(pre->right == NULL)
{
pre->right = current;
current = current->left;
}
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else
{
pre->right = NULL;
printf(" %d ",current->data);
current = current->right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}


outline of what it does

1. take a root node
2. assign into some temporary variable like current
3. check if current is non-null
4. now start a loop until this current is non-null
5. check if current->left is non-null and store in another variable pre
6. if current->left is null, assign current as current->right.
7. otherwise assign pre as current->left
8. start a loop to until you hit either pre->right == null or pre->right == current
9. what it means is that you got successor of current if pre->right == null otherwise you hit the temporary thread created by yourself previously
10. if pre->right == null, create a temp thread , assign pre->right = current, current = current->left
11. if pre->right == current, current = current->right and pre->right = null

Write a method which finds the maximum of two numbers You should not use if-else or any other comparison operator.

sol1:
int c = (a - b) >> 31;
max = c & b | ~c & a;

sol2:
max=(a+b+abs(a-b))/2;
min=(a+b-abs(a-b))/2;

rotating array

problem: Rotate the array a[n] in kth place like this
1 2 3 4 5 6 n= 6 k =3 4 5 6 1 2 3

sol:
1. revert first [0, k] subarray
2. revert last [k+1, n] subarray
3. revert whole of array

find 2 numbers in array with max XOR

yes u heard it right, Max XOR

sol:
create a bin tree with bits
1. if msb is 0, move left
2. if msb is 1, move right
3. till all the numbers are added

now process the array
take ith number
invert it
find the max distance in the tree
return the maximum of distance

adding 2 nos without operator +, *, -

sol1:
using half adder
half adder adds two numbers a and b like

sum = a & b
carry = a^b

int add(int a, int b)
{
if(a == 0) return b;
return (add( (a&b)<<1, a^b) );
' }
sol2:
char *p;
p = (char*)a;
sum = (int)&p[b];
here compiler does the trick :)