C Language Programming: Creation and Traversal of Binary Trees

This program creates a binary tree using a pointer array and implements pre-order, post-order, and in-order traversals of the binary tree.

Input: Number of nodes in the binary tree and traversal method code

Output: Traversal results

#include <stdio.h>

#include <stdlib.h>

//Traversal of binary Tree

//edit by yyh 23/8/2025 12:03

typedef struct tree {

int data;

struct tree *left;

struct tree *right;

} tree;

void print_tree_root(tree *root) {

if (root == NULL) { return; }

printf(“%d “, root->data);

print_tree_root(root->left);

print_tree_root(root->right);

}

void print_tree_left(tree *root) {

if (root == NULL) { return; }

print_tree_left(root->left);

printf(“%d “, root->data);

print_tree_left(root->right);

}

void print_tree_right(tree *root) {

if (root == NULL) { return; }

print_tree_right(root->left);

print_tree_right(root->right);

printf(“%d “, root->data);

}

void type(tree **node) {

int num;

scanf(“%d”, &num);

switch(num) {

case 0:

print_tree_root(node[0]);

break;

case 1:

print_tree_left(node[0]);

break;

case 2:

print_tree_right(node[0]);

break;

default:

printf(“You typed it incorrectly, Please enter again.\n”);

type(node);

}

}

int main(void) {

int i;

int num;

printf(“Please enter the number of the nodes: “);

scanf(“%d”, &num);

printf(“\n”);

tree **node = (tree**)malloc(num * sizeof(tree*));

if (node == NULL) {

printf(“Memory allocation failed\n”);

return 1;

}

for (i = 0; i < num; i++) {

node[i] = (tree*)malloc(sizeof(tree));

node[i]->data = i;

node[i]->left = node[i]->right = NULL;

}

for (i = 0; i < num; ++i) {

if (2 * i + 1 < num) {

node[i]->left = node[2 * i + 1];

}

if (2 * i + 2 < num) {

node[i]->right = node[2 * i + 2];

}

}

printf(“The tree has already created, please enter the traversal method:\n”);

printf(“root: 0\nleft: 1\nright: 2\n”);

type(node);

for (i = 0; i < num; i++) {

free(node[i]);

}

free(node);

return 0;

}

Example of running results:

C Language Programming: Creation and Traversal of Binary Trees

Leave a Comment