当前位置:网站首页 > 更多 > 编程开发 > 正文

[算法刷题] 二叉树的C实现

作者:CC下载站 日期:2022-11-04 00:00:00 浏览:99 分类:编程开发

#include <stdio.h>
#include <stdlib.h>

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<Node *>(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);
}

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯