Friday, March 4, 2016

Traverse tree without recursion and using any data structure

I got this problem statement in one of my technical interviews. I didn't find solution to this problem on google. SO I attempted it myself . It was fun solving this problem and I enjoyed it. Here is solution.


#include
#include
#include
typedef struct node
{
  struct node* left;
  struct node* right;
  struct node* parent;
  int data;
}T;
T* head=NULL;
void add_node(int data)
{
  T* t = (T *)malloc(sizeof(T));
  t->left=NULL;t->right=NULL;t->parent=NULL;t->data=data;
  if (head==NULL) {
   head = t;
  } else {
   T* tmp = head;
   while (1) {
   if (data < tmp->data) {
     // should go on left side
     if (tmp->left==NULL) {
       t->parent=tmp;
       tmp->left = t;
       break;
     }
     tmp=tmp->left;
   } else {
     // should go on right side
     if (tmp->right==NULL) {
      t->parent = tmp;
      tmp->right = t;
      break;
     }
     tmp=tmp->right;
   }
   }
  }
}

void myt(T* root) {
  if (root==NULL) {
    return;
  }
 int left_back=0,right_back=0;

 while(1)
 {
   if (root->left==NULL && root->right==NULL) {
     // I am child node . print my data and move to my parent
     printf(" %d",root->data);
     if (root->parent==NULL) {
       // we are THE ROOT . done traverse
       return;
     }
     if (root==(root->parent)->left) {
       // I was left child of parent
       left_back=1; right_back=0;
     } else {
       // I was right child of parent
       right_back=1; left_back=0;
     }
     root=root->parent;
     continue;
   }

   if (left_back==1) {
     // we have come back from left child   . print data
     printf(" %d",root->data);
     if (root->right!=NULL) {
       root=root->right;  left_back=0;right_back=0;
       continue;
     } else {
       // we dont have right child  . we have to back track
       if (root->parent==NULL) {
  // we are THE ROOT. Done traverse
  return;
       }

       if(root==(root->parent)->left) {
   left_back=1;right_back=0;
       } else {
   left_back=0;right_back=1;
       }
       root=root->parent;
       continue;
     }
   }

   if (right_back==1) {
     // we have come back from right node. we have to back track
     if (root->parent==NULL) {
       // we are THE ROOT. Done traverse
       return;
     }
     if(root==(root->parent)->left) {
       left_back=1;right_back=0;
     } else {
       left_back=0;right_back=1;
     }
     root=root->parent;
     continue;
   }

   if(root->left!=NULL) {
      left_back=0;right_back=0;
      root=root->left;
      continue;
   } else {
    // left child is not present. print data and move to right
    printf(" %d",root->data);
    root=root->right;
    left_back=0;right_back=0;
   }

 }
}

void traverse(T* h) {
  if (h==NULL) {return;}
  traverse(h->left);
  printf(" %d",h->data);
  traverse(h->right);
}
void main()
{
  clrscr();
  printf("\n enter elements \n");
  int n;
  while(1) {
    scanf("%d",&n);
    if(n==0) {
      break;
    }
    add_node(n);
  }
  printf("\n Inorder : ");
  traverse(head);
  printf("\nMinorder : ");
  myt(head);
  getch();
}

Tuesday, April 28, 2015

On getting equal

How many times do you come across phrases such as "I have avenged myself. " "I have taught him a lesson he will remember for his life" "My mind would not rest till I show him for what he is worth. " "wait and see how I deliver my blow" "let my turn come?"

Life has many sides . One of those is to live along with others. It is not possible for you or me to cut ourselves off completely and live by ourselves. The stream of existence is composed of tiny driplets such as you and I. All of us are intrinsically one despite our  separate modes of living and mental reservations. A common bond unites each and every individiual. The human race has evolved out of same parentage and the soul occupying our bodies is one single entity.

In our passage through life and whilst engaged in the struggle for livelihood it is but natural to give our and receive blows. The one who can with stand this knocks best is termed as successful men. Ability to avert getting toppled over by set backs must be acquired. Nature by and large has provided each one of us with equal weapons to fight our battles. Whether you keel the edges of these weapons sharper than your neighbour depends on your own resourcefulness and efforts. Those who are constantly on alert are in the position to take better care of themselves. They in other words minimize the chances of being knocked out. The fight is to be faught with every possible means at your command and every part of your body and mind must be geared to play its part in accordance with demands of the occasion.

The desire to get equal is inborn in human nature. The religious teachers may preach that it is against the wishes of a god to endevour to avenge yourself but from the practical point of view no one can deny that there is pleasure and satisfaction to be derived from returning a blow for a blow. My plea however is that whilst you should leave no stone unturned, no way unexplored and no method untried to bring those who have harmed you to suffer for that do no let the passion envelope you so completely that you forget what is good for you , In striking the enemy do not swing the sword so fast that after slashing through him it injures your own leg. It is important that your peace of mind should not suffer in the process. You should be able to keep your head cool and heart stout. A cool head with stout heart and healthy body can not be matched with any power on earth.

From my personal experience our grievences against others are more often than not a mere figment of imagination. They are mostly based on trivialities. I remember an occasion some ten years ago when i felt an afront at acquaitance of mine not offering me a cigarrete 

Friday, April 24, 2015

ANGER

I was angry with my friend
I told my wrath , my wrath did end.
I was angry with my foe,
I told it not, my wrath did grow.

Anger feeds on our thoughts.  The more we think about it , the more it grows in intensity. Its symptoms are easy to perceive -A bloated face, quivering muscles, shaking body, agitated mind, intense atmosphere. Not altogether a happy combination. A person surcharged with a wrathful feeling can be made out from distance. His feasts will be clenched , teeth closed, eyes red, face set and gait wavering. His emotions hold complete sway over him and , at least for the duration of attack his senses bid him good bye.

I am not saying all this to pull your leg. I know this from personal experience. Anger has had lot to do with setbacks I have come across in life; with ruin friendships and bitterness coupled with irritation at home. A number of frustrations I find on reflections could be avoided if I were able to keep my head cool and temper under control. Imagine what unbridled ire can do to piece at home. Husband comes from his place of work. He is tired, fatigued and somewhat irritated at the way fate has treated him. He is not in happy frame of mind. The need of the hour is for him to pull himself up, shake his head and try to smile or say word of cheer to someone. Such an endevour by itself acts as tonic and serves to clear the mind of the poison infecting it. He does not however take cool of wisdom and falls a pray to the easier but extremely harmful course of giving vent to his irrascible temper by picking up a fault or two with the way his wife has arranged things. It starts a chain reaction. The wife who till his arrival was in joyful mood and in fact looking forward to meeting him is unable to swallow the taunts and replies back with equal venom. Such a flare up if continued may end up in a divorce court. Worst still it will do incalcuable harm to health of both, husband and wife. With the fall in health standard irritation becomes a habitual companion and the irate lips keep on emitting smouldering an embers day in and day out.

What is the out come of all this ? The mind becomes restive , the body feeble and senses corroded. WIth this failings it is difficult to progress on the path of prosperity. Friends leave you one by one. Small and insignificant happenings get magnified in your brain and all sense of proportion is gone

Who would like such as thing happen to him ? Surely no one. Yet knowing fully well the evil effects of anger we fail in taking adequate steps to eradicate it from our being. The consciousness may be there all along that it is bad to get incensed at triflings the will to control is missing.

What is needed in the complete change of process of thinking. Thoughts should never be allowed to dwell on others short comings and effects. Rather a deliberate efforts should be made to remember the good turns done to us, the fine and sympathetic sentiments and feelings expressed by people at times and the realisation that we are not the only ones with unsolved problems. Everyone has his own difficulties. IF each one of us start appreciating this point, the burdens we carry on our shoulders and in our heads would be considerably lightened. Be a cheer to others heart and your soul starts jumping with joy. DO not harbour ill thoughts about others and you would avoid ills approaching you. This is natural law which is supreme and unbreakable.

The feeling of anger usually arises more easily when we are discontented with our lot. The best way to overcome this agony is to try to submerge identity in to others, feel happy in others joys and develop a cheerful disposition. We might at first find it extremely hard to practice but if we persist we would definitely succeed.

Let not the sun go down on your wrath.

Failure to heed this advice might cost you nights sleep. Lack of sleep will make you feel miserable the following day. This will adversely affect your business, your carrier , your prosperity and your relations with those near and dear to you. It is therefore in your interests to carefully weigh the thought conveyed by above statement and decide with a cool head wheather or not it will pay you to follow it.
our
Old testament prescribes a wonderful remedy to keep wrath at an arms distance. It says -
A soft answer turneth a way wrath.
Listen to what john cable says in 'The effect of example '

The deeds we do , the words we say into still air they seem to fleat
We count them ever passed;
but they shall last.
In the dread judgement , they and we shall meet.

Points to remember:
1. ANger is not good for your health and work.
2. Sure cure for it is to speak a word of cheer to those near us
3. Anger begets anger
4. No problems can solved at the anchor sheet of anger 

Sunday, April 19, 2015

Water maintains its level why can't you

Water is one of the natures greatest gifts. In fact 2/3 rd of world of ours consists of water. We must learn something from it. WE must regard its characterisic as guide in many respects. It is the one comodity which perhaps is the dearest to nature as well as human soul. Just recall how shower of rain sends through our system vibrations of romance mirth and cheerfulnes. IS there any living being which does not have water in its assemblage ? BEsides water we actually drink we receive considerable quantity of it from food we eat. ALmost all the different articles of food that we consume contain large quantity of water. If we were to add up all different constitutes of the solid food which we eat every day more than 50 % of it would be water. It is not therefor worth emulating

If you follow a great man you would in due course imbibe some of his greatness . Water is not only great in its own rights but its greatness assumes unsurpassing proportions WHen you consider a good it does to life on this earth. It is senior most partner in running the show of the world. In company vocabulary it is the managing director.

Learn the thing or two from it. The most important quality of water is it maintains its level. Do what you may you cannot make it topsy turvy or hang upside down. If small difficulty and minor irritations upset your mental balance how can you rise to the heights reached by water. Try to be impertureble inexcitable in the face of danger . Maintain your coolness and placidity . The moment it cuts across waters disturbing its even surface it gathers up its folds and resumes its former shape. You cannot make it lose its equanimity

Its endurance and forbearance is unimitable. Put a leg in a pool of water and splash it all around. Remove your leg and you will find it as calm as ever. The tiny drops which you separated from its bulk have rejoined the main body.

Stand along a brook and watch it striving its best to reach its destination and become one with the great ocean. It flows incessantly through hills and plains and overcomes all types of obstacles in its progress. Put a rock in its way and see how it goes over it, under it and round it. Man faced with a difficulty may give up but no , not the stream. No obstruction is too much for it. No hindrance can deflect it from its course and no barrier is too strong to bar its flow. If you put a dam across it to hold it, a day comes when it overflows and rushes again towards its goal.

The problem with which you are surrounded are all capable of solution, given the necessary time and effort. Like the brook you have to go over them, under them and round them. Though soft by itself, water, through sheer perseverance , changes the shape of hard substances such as stone. Big rocks in its way ultimately become small pebbles with which it plays and through which it rustles.

  Small stream and brooklets when they unite become the mighty oceans. There is no distinction in ocean waters about the nationality , colour, creed or religion of its various components. Once they become one, you cannot distinguish between one part and other. In union lies strength is the message conveyed to you by the wateres comprising the oceans. These waters have flowed into it from all the four corners of the world, from all the countries, regardless of whether they are inhabited by whites, blacks, grey or brown people. 

EMULATE WATER AND YOU WILL LEARN TO  MAINTAIN POISE, PEACE, COOLNESS, PLACIDITY,PERSEVERANCE AND UNITY.

    Points to remember.
1. Water maintains its level. you should also strive to do so.
2. Difficulties and irritations should leave you unruffled.
3. Main characteristic of water you must emulate are poise, peace, coolness, placidity, perseverance and unity

Worry part 2

Points to remember
1. Worry does not lead you anywhere . ITs like churning water.
2. Despondency and dispair are utterly hollow and negative aspects of our feelings.
3. A busy executive should always try to keep his head above water.
4. Fear of losses acts as brake on bold and courageous actions
5. Do not allow your expenditure to exceed your income
6. Disappointment in life are common occurrence
7. TO worry about social status is unrealistic
8. DO not become hear broken of unfullfillment of love
9. It is your duty to strive to maintain good health both physical and mental.
10. Do not bother about ingratitude, It is ingrained in human nature.


Worry part-1

Worry is state of mind where currents and cross currents of disturbed thoughts keep on ploughing the mind raising in it many fears and apprehensions of difficulties at hand or expected to take place at a later date. Worst still some minds keep on raking up past mistakes and errors without realising that this tantamounts to digging one's own grave.

It is analogous to churning the water. It carries you nowhere. It may be likened to a farmers effort to raise crops out of a dry and barren piece of land. He may dig it to any depth but it will not yeild any result. What is needed is a tubewell which can make the land fertile enough to help plants and vegetation grow. A worrying mind , if it gets a direction and a purpose could by intensity of its desires achieve some useful ends.

Have you ever ridden a cycle? If its peddle chain is missing no amount of peddling will make it run. THe same position applies to a man given to a worries. He spends days and nights in the company of his torturing thoughts. Peddling them around if only he were turn the gloomy forbiddings to well knit ideas and give some coherence to them. He can hope to make progress in tackling the worries that are worrying them . There is story of father and his 3 sons . THe old man was worrying type. He dreamed that his youngest son was drowned in river. THe middle one was crushed under a train and the eldest died in plane accident. Day and night his mind was worried till he became bedridden. Doctors tried every possible means to restore him to health but to no effect. His mind was terribly upset and hallucinations were taking their tolls. DOctors ultimately gave up the treatment and pronounced the case as hopeless.

Life is what we make it. What we give to it will be returned. If we are particular about resisting the temptations which are harmful to us, we will sow good for ourselves. Material prosperity is much easier to obtain with all your tools intact. If your sword is sharp enough and your hands dextrous at handling it , the enemy will think twice before jumping into fray. If it dares do so, you would be much better fitted to make minced meat out of it.

Despite professions to the contrary , ingratitude is an innate quality of the human mind. A piece of wood in chimney on cold night provides you warmth but in the process burns itself to ashes. Nobody gives it second thought. It is replaced as soon as burnt out. Our mind tends to magnify the good we do but minimize the benefactions we receive, Like rain water sleeping of the umbrella top, it soon forgets the favours bestowed upon us by our well wishers. Why then worry about ingratitude. What others do to us we do to them. It is quits. If someone has been ungrateful for our sacrifices for him , may be we have behaved similarly towards those who have contributed to our well being . Our feelings for others can be compared to a lessons written by a teacher on the blackboard in his class, As soon as it has served his purpose it is wiped out and replaced by a new lesson.

Man is essentially a selfish animal. The instinct of selfishness is the strongest in a child By education and constant sermons his attitude undergoes some modifications as he grows up. Ingratitude is related to this instinct. Where there is a clash between self interest and gratitude the human mind has a tendency to lean to the former.

Old man and women are prone to develop an ache in their heart and feeling of destitution in their minds at their children not returning their love and being grateful for what they did for them, THey should realise that human beings are by nature born with and impulse to look forward and not backward. They would gladly do anything which would make their future secure. But if one expects them to remember and reciprocate what he did to them years ago, he is looking for disappointment. My advice to aged is to keep the purse strings in their hand wherever they possibly can. Those inclined to hand over everything to their children when retired , in the belief that it does not make any difference whether the control is in their or their childrens hand might live to rue their mistake. Not that all children would be inclined to place thier interests above their parents but possibility is always there.


How to Start the working day.

1. Work hard- Tackle the hardest job first
2. Study hard- The more you know the easier and more effective is your work
3. Take the initiative- RUts often deepen into the graves
4. Adore your work- Work well done brings peace to your mind and pleasure to your soul.
5. BE to the point- Haste makes waste and hurry may lead to worry
6. BE courageous and bold- Stoutness of heart with tranquality of mind can make minces meat of all troubles and difficulties.
7. Be cooperative and friendly.
8. Friendlyness is issential for leadership
9. Wear a smile. It will open the door into the sun shine beyond.
10. Develop a transparent and magnetic personality. Personality is to a man what perfume is to a flower.
11. Do your best - IF you give to the world best you have, best will come back to you.
12. BE good to others- that is the key to happiness
13. Never unnecessarrily injure any other mans feelings
14. Keep in mind your responsibilities towards your parents children and wife.
15. Give up obsession with sex.