0% found this document useful (0 votes)
3 views1 page

tree traversal

The document contains a C program that implements a binary tree with functions for creating nodes and performing preorder, inorder, and postorder traversals. It defines a structure for tree nodes and includes a main function that constructs a sample binary tree and displays the results of the traversals. The program prints the traversal outputs to the console.

Uploaded by

Subitsha S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

tree traversal

The document contains a C program that implements a binary tree with functions for creating nodes and performing preorder, inorder, and postorder traversals. It defines a structure for tree nodes and includes a main function that constructs a sample binary tree and displays the results of the traversals. The program prints the traversal outputs to the console.

Uploaded by

Subitsha S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <stdio.

h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* left;
struct node* right;
} Node;
Node* newNode(int data) {
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void preorderTraversal(Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);

preorderTraversal(root->right);
}
}
void inorderTraversal(Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
void postorderTraversal(Node* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}
int main() {
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Preorder traversal of the binary tree is:\n");
preorderTraversal(root);
printf("\n");
printf("Inorder traversal of the binary tree is:\n");
inorderTraversal(root);
printf("\n");
printf("Postorder traversal of the binary tree is:\n");
postorderTraversal(root);
printf("\n");
return 0;
}

You might also like