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:
- First, define the structure of a binary tree node.
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
- 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;
}
- 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;
}
- 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.