二叉树的C实现

2023-08-23 08:07:07 浏览数 (2)

代码语言: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("%dn", 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);
}

0 人点赞