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