Simple tree program in c

Simple tree program in c
A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL.
A Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child

#include<stdio.h>
#include<stdlib.h>

struct node{

 int data;
 struct node *left;
 struct node *right;
};

//create new node when function CreateNode Called

struct node* CreateNode(int data)   //function to create new node & returning a node so return type is struct
{

struct node *new_node=(struct node*)malloc(sizeof(struct node));  //Allocate memory to new node

new_node->data=data;

new_node->left=NULL;
new_node->right=NULL;

return new_node;
}

main()
{

struct node *root;
root=CreateNode(1);

root->left=CreateNode(2);
root->right=CreateNode(3);

root->left->left=CreateNode(3);
root->right->right=CreateNode(4);

}

Related Posts