Thursday, April 17, 2014

In a Binary Tree, find sum of all the nodes below certain level

Given a binary tree, find sum of all the nodes below certain level.

Root is at level 0.
All the children of root are at level 1.
All the grand children of root are at level 2.
and so on.

Given a level n, find some of all the nodes that are at level n or more.

int Sum(Node root, level n)
{
   if(root==NULL)
      return 0;
   if(n>0)
      return Sum(root->left, n-1) + Sum(root->right, n-1);
   return root->data + Sum(root->left, n-1) + Sum(root->right, n-1);
}

No comments:

Post a Comment