Trees are important data structures. In this post, we will explore basic code structures of C to advanced C codes and operations. So flex your muscles and let's climb tree.
basic constructions:
In the following code, I define basic structure of tree using typedef and struct. The driver program creates a tree with two nodes. Please read the program below and watch:
That's why the above program can be extended and used for the construction of longer trees.
For a user input taking tree construction, we have to construct a different program like that. The idea is following:
Let the input be as the nodes will be mentioned first and then the edges will be mentioned after that.
Now, for this construction, we need traversal. Read about tree traversal in this second post.
basic constructions:
In the following code, I define basic structure of tree using typedef and struct. The driver program creates a tree with two nodes. Please read the program below and watch:
#include <stdio.h>
#include <stdlib.h> //without this calloc can not be used
typedef struct node //tree structure definition
{
int data;
struct branch *left;
struct branch *right;
}branch; // here we have set it as branch
branch *createnode(int value) //createnode is the function to create a node of the tree and return it
{
branch *stick;
stick=(branch *)calloc(1,sizeof(branch));
stick->data=value;
stick->left=NULL;
stick->right=NULL;
return stick;
}
//driver program
int main(void)
{
branch *root;
root= createnode(2);
root->left=createnode(5);
root->right=createnode(1);
return 0;
}
See that a tree can be of different types and therefore, a dynamic generation is not possible i.e. just by giving the node values you can not create a tree. You will have to provide the edges properly and then only the tree can be constructed.That's why the above program can be extended and used for the construction of longer trees.
For a user input taking tree construction, we have to construct a different program like that. The idea is following:
Let the input be as the nodes will be mentioned first and then the edges will be mentioned after that.
Now, for this construction, we need traversal. Read about tree traversal in this second post.
Comments
Post a Comment