前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二叉树的C实现

二叉树的C实现

作者头像
SingYi
发布2023-08-23 08:07:07
940
发布2023-08-23 08:07:07
举报
文章被收录于专栏:Lan小站
代码语言:javascript
复制
#include 
#include 

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

typedef struct tree {
    Node *root;
} Tree;

void insert(Tree &tree, int value) {
    Node *node = static_cast(malloc(sizeof(Node)));
    node->data = value;
    node->left = NULL;
    node->right = NULL;
    if (tree.root == NULL) {
        tree.root = node;
    } else {
        Node *temp = tree.root;
        while (temp != NULL) {
            if (value < temp->data) {
                if (temp->left == NULL) {
                    temp->left = node;
                    return;
                } else {
                    temp = temp->left;
                }
            } else {
                if (temp->right == NULL) {
                    temp->right = node;
                    return;
                } else {
                    temp = temp->right;
                }
            }
        }
    }
}

void display(Node *node) {
    if (node != nullptr) {
        display(node->left);
        printf("%d\n", node->data);
        display(node->right);
    }
}

int main() {
    int arr[7] = {6, 3, 8, 2, 5, 1, 7};
    Tree tree;
    tree.root = NULL;
    for (int i = 0; i < 7; ++i) {
        insert(tree, arr[i]);
    }
    display(tree.root);
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年11月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档