0% found this document useful (0 votes)
2 views

Tree Tarversal Code

The document provides a C implementation of a binary tree, including the structure for a tree node and functions to create a new node and build the tree recursively. It also includes functions for preorder, inorder, and postorder traversals of the binary tree. The main function prompts the user to build the tree and confirms its successful creation.

Uploaded by

manavsharma90018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Tree Tarversal Code

The document provides a C implementation of a binary tree, including the structure for a tree node and functions to create a new node and build the tree recursively. It also includes functions for preorder, inorder, and postorder traversals of the binary tree. The main function prompts the user to build the tree and confirms its successful creation.

Uploaded by

manavsharma90018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Implementation of Binary Tree

// Structure for a tree node


struct Node {
int data;
struct Node *left, *right;
};

// Create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Create a binary tree recursively


struct Node* buildTree() {
int value;
printf("Enter node value (-1 for NULL): ");
scanf("%d", &value);

if (value == -1)
return NULL;

struct Node* newNode = createNode(value);

printf("Enter left child of %d:\n", value);


newNode->left = buildTree(); // Create left subtree

printf("Enter right child of %d:\n", value);


newNode->right = buildTree(); // Create right subtree

return newNode;
}

int main() {
printf("Build the binary tree:\n");
struct Node* root = buildTree();
printf("Binary tree created successfully.\n");
return 0;
}
Preorder traversal (Root, Left, Right)
void preorderTraversal(struct Node* root) {
if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

Inorder traversal (Left, Root, Right)


void inorderTraversal(struct Node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}

Postorder traversal (Left, Right, Root)


void postorderTraversal(struct Node* root) {
if (root == NULL)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}

You might also like