Monday, January 6, 2014

Given a Binary Tree, replace the data of each node by the sum of data of all its descendent nodes.(Leaf nodes will have 0)

The Solution for this problem is simple and recursive one. In this problem you have to traverse to the last parent node which has at least 1 child.

So the conditions possible are:

  1. Parent has only one leaf  node a) only Left Leaf Node or b) only Right Leaf Node
  2. Parent has both children, Left and Right Leaf Nodes.
Now the only thing left is to traverse recursively to the last parent and check wether it has one child or 2 children and store the value of its child or sum of children into its info and if the children do not have any further children then set their value to 0.

#include <stdio.h>
#include <stdlib.h>

struct BST
    struct BST* left;
    int info;
    struct BST* right;

struct BST* newNode(int);
void printTree(struct BST*);
void replaceParentWithSumOfChildren(struct BST*);