Sunday, April 10, 2011

WAP to Print New Binary Tree in which each njode has sum of its left & right subtree , from Given BT

#include
#include

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}


struct node* sumSubTree(struct node** root)
{
int LeftOld,RightOld;
struct node *l,*r;
if((*root) == NULL || ((*root) -> left== NULL && (*root)->right == NULL))
return NULL;
else
{
LeftOld = (*root)->left->data;
RightOld = (*root)->right->data;
l = sumSubTree(&(*root )->left);
r = sumSubTree(&(*root)->right);
(*root)->data = LeftOld + RightOld;
if(!l)
(*root)->data += l->data;
if(!r)
(*root)->data += r->data;
return *root;
}

}

/* Given a binary tree, print its nodes in inorder*/
void printPreorder(struct node* node)
{
if (node == NULL)
return;

/* first print data of node */
printf("%d ", node->data);

/* then recur on left sutree */
printPreorder(node->left);

/* now recur on right subtree */
printPreorder(node->right);
}

int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

root=sumSubTree(&root);

printf("\n Preorder traversal of binary tree is \n");
printPreorder(root);



getchar();
return 0;
}

Run Here https://ideone.com/irlOz

No comments :