Data structures in C Series 6.1 : Implementing a Binary Tree

Implementing Binary Tree Step 1 | Binary Search Tree : 

The following is definition of Binary Search Tree(BST) according to Wikipedia

Binary Search Tree, is a node-based binary tree data structure which has the following properties:

The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.


#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};

struct node* newnode(int item)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

struct node * insert(struct node* node, int key)
{
if(node == NULL)
{
return newnode(key);
}
else
{
if(key < node->key)
node->left =insert(node->left,key);

else
node->right =insert(node->right,key);

}
return node;
}

void inorder(struct node *node)
{
if(node != NULL)
{
inorder(node->left);
printf("%d \n",node->key);
inorder(node->right);
}
}

int main()
{
struct node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
    // print inoder traversal of the BST
    inorder(root);
    return 0;
}


'''
Output
20
30
40
50
60
70
80
'''

Comments

  1. if(node == NULL)
    {
    return newnode(key);
    }
    else
    {
    if(key < node->key)
    node->left =insert(node->left,key);

    else
    node->right =insert(node->right,key);

    }



    return node; // Why we have done this ?


    In the insert function why we have to return node at the end.

    Please explain. I am confused.

    ReplyDelete
    Replies
    1. The code will work just fine even without the (return node;) it was just as precaution but yes its definitely useless.

      Delete

Post a Comment

Popular Posts