Create Binary Tree in C: Step-by-Step Guide

In C language, one can use a struct to represent a binary tree node, and then create the binary tree recursively. The specific method is as follows:

  1. First, define the structure of a binary tree node.
typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;
  1. Create a function to recursively build binary tree nodes.
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}
  1. Create a function to build a binary tree.
Node* createBinaryTree() {
    Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);
    return root;
}
  1. You can modify the code above as needed to build different binary trees. After creating the binary tree, you can perform operations such as traversals to manipulate the binary tree.
bannerAds