Saturday, April 19, 2014

In Binary Tree, Find Sum of Nodes of Alternate Levels

Given a binary tree, find sum of all the nodes of alternate levels.

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 alternate levels 0, 2, 4, and so on.

int Sum(Node root, level n)
      return 0;
   int d = (n%2 == 0 ? root->data : 0);
   return d + Sum(root->left, n+1) + Sum(root->right, n+1);

No comments:

Post a Comment