了解二叉搜索树

Understanding the Binary Search Tree

struct node {
    int key;
    struct node* left;
    struct node* right; 
};

struct node * newBST(int key){
    struct node* temp = (struct node*) malloc(sizeof(struct node));
    temp -> key = key; 
    temp -> left = temp -> right = NULL; 
    return key; 
}

所以我无法理解为什么我们malloc节点的大小?构造 *temp ? 是不是这样我们就可以访问在节点中创建的元素?

预留内存。在 struct node {...} 之后,您现在基本上已经有了关于节点应该是什么样子的蓝图。然后你去 urban 记忆规划办公室,告诉他们 "I'm making a new node, can I reserve 24 square meters bytes somewhere?" 他们告诉你 "Sure, this here should be a good place, we promise not to give it to anyone else. Just make sure not to mess with anything outside those 24 square meters bytes, or bad things will happen"。所以你带着你的temp地址,去那里开始布置东西:key进入这些 8 平方米字节,让我们清理 these 8 和 these other 8 之前可能存在的所有问题...


*) int 现在通常占用8字节内存,每个指针也是如此。但这取决于您的计算机和编译器。