Popular Posts

Wednesday, July 13, 2011

Check if a given Binary Tree is SumTree

Write a function that returns true if the given Binary Tree is SumTree else false. A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree. An empty tree is SumTree and sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree.
Following is an example of SumTree.


            26
          /   \
         10    3 
       /    \    \
      4     6     3 



Solution:
For each node check the following,

Right child  : non-leaf
Left child   : non-leaf
  root->data==2*root->left->data + 2*root->right->data.

Right child  : leaf
Left child   : leaf 
 root->data==root->left->data + root->right->data.

Right child  : leaf
Left child   : non-leaf
 root->data==2*root->left->data + root->right->data.

Right child  : non-leaf
Left child   : leaf
 root->data==root->left->data + 2*root->right->data.

Code:
int isSumTree_reentrant(Tnode *root) {
    if (root == NULL)
        return 0;
    if (isleaf(root) == 1)
        return 1;
    int nleft = 0, nright = 0;
    if (root->left != NULL) {
        nleft = root->left->data;
        if (isleaf(root->left) == 0)
            nleft = 2 * nleft;
    }
    if (root->right != NULL) {
        nright = root->right->data;
        if (isleaf(root->right) == 0)
            nright = 2 * nright;
    }
    if (root->data != nleft + nright)
        return 0;
    int a = 1, b = 1;
    if (root->left != NULL)
        a = isSumTree_reentrant(root->left);
    if (root->right != NULL)
        b = isSumTree_reentrant(root->right);
    return a & b;
}

No comments:

Post a Comment