Skip to content

Commit

Permalink
Merge pull request #90 from GovindaRohith/GovindaRohith-dsa-worksheet
Browse files Browse the repository at this point in the history
Added treetransversal.c
  • Loading branch information
lilmistake authored Oct 26, 2023
2 parents 0beb059 + ad5d207 commit c638ab0
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
78 changes: 78 additions & 0 deletions DSA_Codesheet/C/treetransversal.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#include<stdio.h>
#include<stdlib.h>
#include <stdbool.h>
struct node
{
int data;
struct node *left,*right;
};
typedef struct node Node;
bool first;
// Function to perform In-Order Traversal
void inOrderTraversal(Node* root) {
if (root == NULL) return;
inOrderTraversal(root->left);
if (!first) printf(" -> ");
printf("%d",root->data);
first = false;
inOrderTraversal(root->right);
}
// Function to perform Post-Order Traversal
void postOrderTraversal(Node* root) {
if (root == NULL) return;
postOrderTraversal(root->left);
postOrderTraversal(root->right);
if (!first) printf(" -> ");
printf("%d",root->data);
first = false;
}

// Function to perform Pre-Order Traversal
void preOrderTraversal(Node* root) {
if (root == NULL) return;
if (!first) printf(" -> ");
printf("%d",root->data);
first = false;
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
Node * createNode(int data){
Node *root=malloc(sizeof(Node));
root->data=data;
root->left=NULL;
root->right=NULL;
}
int main() {
// Creating a sample binary tree
Node* root = createNode(1);
root->left = createNode(12);
root->right = createNode(9);
root->left->left = createNode(5);
root->left->right = createNode(6);


first = true;

printf( "In-Order Traversal: ");
inOrderTraversal(root);
printf("\n");

first = true;
printf( "Post-Order Traversal: ");
postOrderTraversal(root);
printf("\n");

first = true;
printf( "Pre-Order Traversal: ");
preOrderTraversal(root);
printf("\n");

// Clean up: Delete nodes to avoid memory leaks
free(root->left->left);
free(root->left->right);
free(root->left);
free(root->right);
free(root);

return 0;
}
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,3 @@ Distributed under the MIT License. See `LICENSE` for more information.
</a>
</td></tr>
</table>
<!-- readme: collaborators,contributors -end -->

0 comments on commit c638ab0

Please sign in to comment.