Level sum of the nodes in Binary Tree

vertical (column) sum of  a binary tree.

Example:

      1
    /    \
  2        3
 / \      / \
4   5   6   7

The tree has 5 vertical lines

Vertical-1: nodes-4 => vertical sum is 4
Vertical-2: nodes-2 => vertical sum is 2
Vertical-3: nodes-1,5,6 => vertical sum is 1+5+6 = 12
Vertical-4: nodes-3 => vertical sum is 3
Vertical-5: nodes-7 => vertical sum is 7

We need to output: 4 2 12 3 7

Implementation:

void get_Vertical_Sum(Tree* T,int[] sum,int column)
{
   if(T==NULL)
      return;
   else
   {
     verticalSum[column]+=T->data;
     get_Vertical_Sum(T->left,column-1);
     get_Vertical_Sum(T->right,column+1);
   }
}

Horizontal (level) sum of a binary tree

Example:

    5
  /  \
 3    8
/ \  / \
1 4  6 10

for this tree a[0]=5, a[1]=11, a[2]=21…..

Implementation:

void get_Horizontal_Sum(Tree* T,int[] sum,int level)
{
   if(T==NULL)
      return;
   else
   {
     sum[level]+=T->data;
     get_Horizontal_Sum(T->left,level+1);
     get_Horizontal_Sum(T->right,level+1);
   }
}

About ashishlahoti

exercise you brain using this blog View all posts by ashishlahoti

Leave a comment