mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 06:49:36 +03:00
Include Data Structures and start with Binary Trees
This commit is contained in:
parent
fd8d20e907
commit
ac15243b2a
39
data_structures/binary_trees/create_node.c
Normal file
39
data_structures/binary_trees/create_node.c
Normal file
@ -0,0 +1,39 @@
|
||||
/* Includes structure for a node and a newNode() function which
|
||||
can be used to create a new node in the tree.
|
||||
It is assumed that the data in nodes will be an integer, though
|
||||
function can be modified according to the data type, easily.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
struct node
|
||||
{
|
||||
struct node *leftNode;
|
||||
int data;
|
||||
struct node *rightNode;
|
||||
};
|
||||
|
||||
struct node *newNode(int data)
|
||||
{
|
||||
struct node *node = (struct node *)malloc(sizeof(struct node));
|
||||
|
||||
node->leftNode = NULL;
|
||||
node->data = data;
|
||||
node->rightNode = NULL;
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
/* new node can be created here as :-
|
||||
|
||||
struct node *nameOfNode = newNode(data);
|
||||
|
||||
and tree can be formed by creating further nodes at
|
||||
nameOfNode->leftNode and so on.
|
||||
*/
|
||||
|
||||
return 0;
|
||||
}
|
45
data_structures/binary_trees/recursiveTraversals.c
Normal file
45
data_structures/binary_trees/recursiveTraversals.c
Normal file
@ -0,0 +1,45 @@
|
||||
/* Includes the functions for Recursive Traversals
|
||||
of a Binary Tree. It is assumed that nodes and
|
||||
tree have been created as per create_node.c
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
void inOrderTraversal(struct node *node)
|
||||
{
|
||||
if(node == NULL) //if tree is empty
|
||||
return;
|
||||
|
||||
inOrderTraversal(node->leftNode);
|
||||
printf("\t%d\t", node->data);
|
||||
inOrderTraversal(node->rightNode);
|
||||
}
|
||||
|
||||
void preOrderTraversal(struct node *node)
|
||||
{
|
||||
if(node == NULL) //if tree is empty
|
||||
return;
|
||||
|
||||
printf("\t%d\t", node->data);
|
||||
preOrderTraversal(node->leftNode);
|
||||
preOrderTraversal(node->rightNode);
|
||||
}
|
||||
|
||||
void postOrderTraversal(struct node *node)
|
||||
{
|
||||
if(node == NULL) //if tree is empty
|
||||
return;
|
||||
|
||||
postOrderTraversal(node->leftNode);
|
||||
postOrderTraversal(node->rightNode);
|
||||
printf("\t%d\t",node->data);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
/* traversals can be done by simply invoking the
|
||||
function with a pointer to the root node.
|
||||
*/
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user