Tuesday, November 19, 2013

Size of a Binary Tree

Write a Program to find Size of a Binary Tree
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node* left;
    struct node* right;
} Node;

 Node * addNode (int data)
{
    Node *temp = (Node *) malloc (sizeof (Node));
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

 int size (Node *root)
{
    if (root == NULL)
        return 0;
    return (size(root->left) + size(root->right) + 1);
}

int main ()
{
    Node *root = addNode(1);
    root->left = addNode(2);
    root->right = addNode(3);
    root->left->left  = addNode(5);
    printf("size of binary tree is %d\n",size(root));
    return 0;
}

No comments:

Post a Comment