Binary Tree Traversal


I thought long before of writing this post after discussing the binary tree generation in reverse lexicographic order but unfortunately it got delayed. So lets not make any more delay in discussing binary tree traversal.

Following are the general way of traversing binary tree, which you can find in any data structure book:-

1) Preorder :-

sample recursive code:


Non-recursive traversal:-

            stack S;
            while(p is not null or S is not empty) 
              if(p is not null)
                    if(left(p) is not null)
                           if( S is not empty)
                     }while(S is not empty and q is rtptr);


2) Inorder :-


3) Postorder :-


4) Level-wise binary tree traversal.

We can have some more traversal based on the way we traverse left and right child. But here all the traversal require some extra data structure like stack. Hence we will discuss some more tree traversal which are space effective.

Link Inversion Traversal

This is very space effective and beautiful algorithm. In which we assign 1 bit extra information which store  0 or 1.  Initially, all the node have 0. As we descend to the right, we tag that node as 1 and make the right pointer of the node point to parent, whose right subtree is to be traversed. And as we descend to the left, we tag that node as 0 and make the left pointer point to parent, whose left subtree is to be traversed. Once we finish the traversing the subtree, can look at the tag of the node and decide whether it was the left or right subtree of the parent whose traversal has just been finished, this way we traverse back up to root. While traversing, we should restore the tag and its pointers also.

This tree traversal does not require any additional data structure and it just need n extra bit to tag each node. Lets improve this also.

Robson Traversal

This is even more space effective than the “Link Inversion Traversal”, since it does not require even  n bits extra information. It uses the leave node to store the information, basically it connects all the leave node and use them as stack and hence we need an extra pointer to point to start or end of this stack and we call that pointer as stack and one more extra pointer we will call that top,which will point to the last (recent) traversed node whose right tree we are traversing and which have non null left subtree and stack pointer’s right will point to the next most recent and its left pointer will point to the next leave node who will store the similar information.

Here is the algorithm:-

Discussion for Integer Overflow in Java


Today, I was reading an article for overflow and cannot stop myself from sharing the gist of it.

Let us discuss this solution of binary search tree.

public int binarySearchTree(int a[],int item)
  int start=0;
  int end=a.length-1;
      int mid=(start+end)/2;
               return mid;
      else if(a[mid]<item)
return -1;


if we carefully check these lines of code, we will realize that the line mid=(start+end)/2 may result in overflow, what if start+end > Integer.MAX_VALUE then mid will have a -ve value.  To overcome this sort of potential programming bug (this bug is still existing in Java’s Arrays Binary search and it has been earlier reported by Joshua Bloch) , it will be better to write this line of code as this,

1)  mid= start + (end-start)/2;
2) mid = (start+high) >>>1; //since in java “>>>” is unsigned right shift operator.
Now let us try to write a utility class to check whether different arithmetic operation is overflow safe or not.

For this let us start to discuss which all arithmetic operation can result in overflow, here I will like to point out that any logical operation like &, | and ^ cannot result in overflow thats why we are only discussing arithmetic operation.

1) Addition:  a+ b can result in overflow as we have seen in above discussion. So, we need to have a utility method for this.

2)  Subtraction: same like for addition it can also result in overflow.

3)  Multiplication: a*b, can easily result in overflow.

4) Division: consider this case Integer.MIN_VALUE/-1,  this will result in overflow.

5) Negation: – (Integer.MIN_VALUE) can result in overflow again.


Here is the Utility class has methods to check the safety for each of the above discussed arithemetic operations:-

package org.aakash.pratice;

public class OverflowCheckUtility {

public static boolean isSafeToSubtract(int i,int j)
          return (i&Integer.MIN_VALUE)<0;
    return isSafeToAdd(i, -j);
public static boolean isSafeToNegate(int i)
    return i!=Integer.MIN_VALUE;
public static boolean isSafeToAdd(int i,int j)
    int k=i+j;
         return false;
    return true;
public static boolean isSafeToDivide(int i,int j)
      return false;
   return true;
public static boolean isSafeToMultiply(int i,int j)
   int k=i*j;
   boolean expectedSign=((i&Integer.MIN_VALUE)^(j&Integer.MIN_VALUE))>=0?true:false;
   boolean actualsign=(k&Integer.MIN_VALUE)>=0?true:false;
   return expectedSign==actualsign;
   Testing utility class for different boundry values
* @param args

public static void main(String[] args) {
// TODO Auto-generated method stub
     int count=0;
     int n=Integer.MIN_VALUE;
//        int n=-1;
     System.out.println("::checking for multiply");
     int i=-1;
     System.out.println(isSafeToMultiply(i, Integer.MIN_VALUE));
     System.out.println(isSafeToMultiply(i, Integer.MAX_VALUE));
     System.out.println(isSafeToMultiply(2, Integer.MAX_VALUE/3));
     System.out.println(isSafeToMultiply(2, Integer.MAX_VALUE/2));
     System.out.println(isSafeToMultiply(2, Integer.MAX_VALUE));
     System.out.println(isSafeToMultiply(-2, Integer.MIN_VALUE/2));

     System.out.println("checking subtraction");
     System.out.println(isSafeToSubtract(-1, Integer.MAX_VALUE));
     System.out.println(isSafeToSubtract(-2, Integer.MAX_VALUE));
     System.out.println(isSafeToSubtract(-5, Integer.MAX_VALUE));
     System.out.println(isSafeToSubtract(1, Integer.MIN_VALUE));
     System.out.println(isSafeToSubtract(-12, Integer.MIN_VALUE));
     System.out.println(isSafeToSubtract(-1, Integer.MIN_VALUE));

     System.out.println("checking addition");
     System.out.println(isSafeToAdd(-1, Integer.MIN_VALUE));
//        System.out.println(isSafeToSubtract(-2, Integer.MAX_VALUE));
//        System.out.println(isSafeToSubtract(-5, Integer.MAX_VALUE));
//        System.out.println(isSafeToSubtract(1, Integer.MAX_VALUE));


How to generate all possible binary tree in reverse lexicographic order


Suppose we are representing binary as L and R array, for example
The tree would be represented then
1            L[1]=2, R[1]=4
/  \           L[2]=0, R[2]=3
2   4        L[3]=0, R[3]=0
\             L[4]=0, R[4]=0

Now, if we read tree in preorder, in such a way that if node present it print 1 otherwise 0 then this tree will also be represented as 110100100. Now the problem we are going to solve here is: “ if we have to generate all possible binary tree for a give number of node in such a way that if we traverse the tree in preorder just described then it should be in reverse lexicographic order.

Now, first we will develop the algo then will code it.

Our first step will be to observe the pattern and see what will be the next generated tree for a given tree. Suppose we have this tree






tree in 1,0 format : 1110000

then the next generated tree in the reverse lexicographic order will be this






tree in 1,0 format : 1101000

After looking at then newly generated tree, we can find that node 3 has moved and its moved from left of 2 to right of 3.  Let us generate one more tree from the last generated tree and the new tree will look like this:


            /       \

          2            3

tree in 1,0 format : 1100100 (Note: observe this no for all the generated tree, you will find its decreasing)

and next  tree generated from this tree is:


             /   \

        null      2

                   /      \

              3          null

tree in 1,0 format : 1011000 (Note: observe this no for all the generated tree, you will find its decreasing)

If we compare with the last generated one then we will find that this time node 2 has moved and now node 3 is left child of node 2.  If we generate  some more trees then we will find that this algo:

1. take the nth node and try to find the best position for it i.e. the next possible position for it in preorder.

2. if we are not able to find any position for nth node then try to find for n-1 th node and moved the node there

and then we make all node greater then this left child of its parent.

For example :-

1 we take the first generated tree as an example here:

1. let us take the nth node , 3 in this case, now try to find the next possible position for it in the tree after traversing it in preorder then we will find that it it is the right of 2nd node.

2. move the 3 rd node to right of 2nd node and since it has no child node, hence this is the answer.

2. Now try, the last generated tree:

1. let us take the nth node first here i.e. 3rd node in this case, now if we try to next possible position. We see there is no possible next position for so

2. try the node higher then it i.e. 2nd node. We find that next possible position for it is right of 1. Now shift 2nd to this new position and move 3 rd as its left child, if we have 4 th node then we would have made it left of 3rd.

The most important this, we have to do now, is to find the way to find the next possible position for the given node. After,  we do pre-order traversal of the tree then we will find that the 3 rd node traversed after traversing the selected node is the possible position for it. For example,

take the example of first generated tree:-


                       /       \

                      2           null 4

                  /    \

              3         null 3

             /    \

     null  1   null 2

now if we try to find , the possible position for 3 we see that after traversing node 3 in pre-order, we traverse null 1 first then null 2 and then null3 which is the possible position and which is exactly third node traversed after traversing node 3. Hence our logic is correct in this example.

Now, we consider the last generated tree, the parent tree is


                                  /      \

                              2             3

                         /     \             /   \

                 null1  null2     null3  null4

Now, we try to find,  best  position for nth node, i.e. 3 rd node, now if we do pre-order traversal, then we find that after traversing node 3rd we can only 2 nodes which are its child and hence there is no possible shift for node 3 rd hence we will do the same for node 2 nd and we will find that 3 rd node traversed after traversing node 2 is the node where currently node 3 is, hence we shift 2 to this new position and make node 3 its left child and if we would has 4 th node then it would have been the left child of node 3rd and so on.

Before we start coding, one more point left to discuss is: from where to start, what actually I mean is what will be the first base tree?

For, generating the reverse lexicographic order  tree, the firs tree should be the left linear tree i.e.









and the final tree will be right linear tree i.e.










Linux CPU Scheduling


Today we will discuss about the CPU scheduling in Linux. What do we mean by CPU scheduling, it is sharing the CPU among different processes. Earlier most of the system were uniprocessor and for them CPU scheduling algorithm used were:-

  1. FCFS (First come first scheduled)
  2. SJFS (Shortest Job First)
  3. RR (Round Robin)
  4. Priority Based Scheduling

Nowadays systems are multiprocessor and we need to schedule the CPU in such a way that all the processor execute jobs in balanced way and for this we have new scheduling algorithms. Besides this most of the new scheduling algorithm are priority based.

Now, when we consider the priority based algorithm, then first question arise is: who will assign the priority? we cannot leave this to user; since it may possible that the user processes will have higher priority then the system related processes which is not correct since the interrupt and kernal thread should have higher priority and we also cannot leave the priority decision totally on the system since then it will be impossible for user to specify to the system about importance of tasks. In Linux there are two types of priorities:-

  • Static Priority- assigned by the user using nice() system call.
  • Dynamic Priority – priority assigned earlier is recalculated by the scheduler.

In, Linux processes are classified as:-

  • CPU bound processes (Real Time (RT) processes)
  • IO bound processes (Interactive processes)

Scheduler in Linux system is known as O(1) scheduler, since it takes constant time in all the operations e.g. selecting the process with highest priority, recalculating the priorities and adding the process to queue.It is multi-level priority based, fairer and preemptive(once the time quantum is over it will be switched with the process higher or equal in priority and time quantum assigned to processes is nearly ~100 ms) in nature. There are 140 levels of priority and at each level there is queue for processes.For deciding, the processes with highest priority it uses bitmap mechanism and scan this bitmap array from left and so which ever bit is found to be set first, process will be selected from that particular priority level.
In Linux, typically there are two priority arrays (as discussed earlier the array of 140 priority queue) are maintained, which are known as active and expired. For, processes for whom time quantum is over, is moved to expired array and once the processes are exhausted in active array, pointers are exchanged that is expired array become active and active become expired and all processes are assigned new time quantum (a.k.a epoch).

While recalculating the priority, scheduler gives bonus to processes which varies from 0 to 10, one thing
to be remembered is that higher the value of the priority less is its priority in scheduler term, hence to increase the priority, bonus added which actually means decrementing that many bonus from the current priority and opposite way while decreasing the priority in scheduler context. To make the system fairer, IO bound processes get more bonus then the CPU bound and this bonus calculation is depend on the amount processes have slept and priorities for RT processes remains same. Algorithm for recalculation of priority of process is:

(For detail, data structure and methods of Linux check kernel/sched.c and kernel/sched.h file and man sched_setscheduler.)

bonus = CURRENT_BONUS(p) – MAX_BONUS / 2;
prio = p->static_prio – bonus;
CURRENT_BONUS is defined as follows:

Essentially, CURRENT_BONUS maps a task’s sleep average onto the range 0-MAX_BONUS, which is 0-10. If a task has a high sleep_avg, the value returned by CUR-RENT_BONUS will be high, and vice-versa. Since MAX_BONUS is twice as large as a task’s priority is allowed to rise or fall (MAX_BONUS of 10 means that the priority adjustment can be from +5 to -5), it is divided by two and that value is subtracted from CURRENT_BONUS(p).

Here, p-> static_prio is the static priority defined by the user to a process using nice() system call and by default it is 0.

Till now we have discussed about the priority assignment and its recalculation and data structure and algo for processes priority, but for a scheduler to be fairer to all processor it must need to balance the jobs load among the processors. For this load balancing for SMP system, Linux scheduler invokes the rebalance_tick() function, which is called by scheduler_tick(). rebalance_tick() first updates the current CPU’s load variable, then goes up the CPU’s scheduler domain hierarchy attempting to rebalance.

We can also specify different types of scheduling policies and details for this can be found, if we do “man sched_setscheduler”.
In summary, Linux CPU scheduler is one of the best multi-processor and fairer scheduler available today.

Synchronization using Monitor



It is an advance mechanism for synchronization, it is more sophisticated and advance than “Semaphore”. It can be considered as an object or module where the variables and synchronization mechanism is abstracted from the user hence unlike semaphore where user is suppose to handle the mutual exclusion and counting based logic, hence less error-prone.

It has been invented by C. A. R. Hoare, a british computer scientist who is profoundly known for inventing Quick Sort.

At a time only one thread can execute monitor’s procedure and only one of the procedure of monitor can be executed. From implementation point of view we can use binary semaphore to implement this feature of monitor .i.e. to provide the mutual exclusion among the monitor’s procedures.

Now, since only one of thread can execute the monitor hence other thread should wait for it and for waiting we need to first have the queue and then method call to make them wait () and release them from the waiting queue and having this in mind a new concept of Condition Variables is introduced. The POSIX thread implementation has library for this pthread_cond_wait() and pthread_cond_signal().

Though Condition variables’s wait() and signal() and Semaphore’s P() and V() seems similar but there are some differences:-

  • Wait Queue is FIFO (hence it is considered as fair also), unlike the semaphore queue, hence process will be awake in order
  • Unlike V() of semaphore, if there is no process waiting then signal() call will be nop (no operation)
  • Condition variable can only be used for block and wake up, it cannot be used for counting
  • Executing wait(), release mutual exclusion on the monitor i.e. allow other thread to execute it

Some caveats while implementing monitor:-

  • We should call signal() as the last instruction otherwise two threads will be executing the monitor at the same time which is not what we are expecting, those two threads will be: the thread which called signal() and the one which is waked up.
  • If we are calling signal in the middle then use the concept of urgent queue which is again like wait queue. The thread which is calling signal() will be inserted in urgent queue and if there is no process waiting for that signal then threads waiting in the urgent queue will be waked up and it has given priority over threads on the entrance queue (There is supposed to be an entry queue for the thread willing to get in monitor)

In the Java language, each object may be used as a monitor. (However, methods that require mutual exclusion must be explicitly marked as synchronized.) Rather than having explicit condition variables, each monitor (i.e. object) is equipped with a single wait queue, in addition to its entrance queue. All waiting is done on this single wait queue and all notify and notify all operations apply to this queue.

This approach has also been adopted in other languages such as C#.


Hello world!


Hi Guys,

I am Aakash, currently a graduate student at Temple University, Philadelphia before joining Temple I worked as Senior Quality Eng. in Yahoo! R&D for 3 and half years. I am also an alumni of Vellore Institute of Technology, Vellore, India.
I believe in working hard and doing something new in my style. I am fond of computers and love solving problems, optimizing it and my area of interests are: Programming Technique. Algos, Operating System and Distributed Systems.
As far as my hobbies and interests are concerned I like coding, reading books, listening songs and watching Cricket and Football.

I will welcome readers to be my friend at FB ( and will appreciate their comments.

Thanks for ur precious time!