二叉树的C实现

Lan
Lan
2022-11-04 / 0 评论 / 72 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月04日,已超过750天没有更新,若内容或图片失效,请留言反馈。
#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);
}
0

评论 (0)

取消