C语言实现二叉树数据结构完整代码及分享

二叉树实验.cpp

在本篇内容中,您将看到个人编写的二叉树数据结构的C语言代码。代码实现了基础的二叉树构建、插入和遍历功能。

代码内容

以下是二叉树的C语言实现,适合对数据结构有一定了解的读者。注意:代码可能存在不足之处,分享此代码促进交流和学习。

// 二叉树节点定义
#include 
#include 

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

// 创建新节点
struct Node* newNode(int data) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// 插入节点(样例实现)
struct Node* insert(struct Node* root, int data) {
    if (root == NULL) {
        return newNode(data);
    }
    if (data < root>data) {
        root->left = insert(root->left, data);
    } else if (data > root->data) {
        root->right = insert(root->right, data);
    }
    return root;
}

// 中序遍历
void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    struct Node* root = NULL;
    root = insert(root, 10);
    insert(root, 5);
    insert(root, 15);
    inorder(root);
    return 0;
}

代码说明

上述代码实现了二叉树节点的定义、新节点的创建、节点的插入及中序遍历。通过insert函数,可以将元素按照二叉树规则插入适当的位置。inorder函数则是经典的中序遍历,实现了对二叉树的结构化输出。

总结

该二叉树数据结构代码适合入门C语言的数据结构学习者,但请注意,该代码可能尚有优化空间,欢迎修改完善。

cpp 文件大小:1.74KB