我的问题与以下代码有关(请注意,我在此处询问了有关代码不同区域的相关问题):
#include <stdio.h>
#include <stdlib.h>
struct node
{
int v;
struct node * left;
struct node * right;
};
typedef struct node Node;
struct bst
{
Node * root;
};
typedef struct bst BST;
BST * bst_insert(BST * tree, int newValue);
Node * bst_insert_node(Node * node, int newValue);
void bst_traverseInOrder(BST * tree);
void bst_traverseInOrderNode(Node * node);
int main(void)
{
BST * t = NULL;
t = bst_insert(t, 5);
bst_insert(t, 8);
bst_insert(t, 6);
bst_insert(t, 3);
bst_insert(t, 12);
bst_traverseInOrder(t);
return 0;
}
BST * bst_insert(BST * tree, int newValue)
{
if (tree == NULL)
{
tree = (BST *) malloc(sizeof(BST));
tree->root = (Node *) malloc(sizeof(Node));
tree->root->v = newValue;
tree->root->left = NULL;
tree->root->right = NULL;
return tree;
}
tree->root = bst_insert_node(tree->root, newValue);
return tree;
}
Node * bst_insert_node(Node * node, int newValue)
{
if (node == NULL)
{
Node * new = (Node *) malloc(sizeof(Node));
new->v = newValue;
new->left = NULL;
new->right = NULL;
return new;
}
else if (newValue < node->v)
node->left = bst_insert_node(node->left, newValue);
else
node->right = bst_insert_node(node->right, newValue);
return node;
}
void bst_traverseInOrder(BST * tree)
{
if (tree == NULL)
return;
else
{
bst_traverseInOrderNode(tree->root);
printf("\n");
}
}
void bst_traverseInOrderNode(Node * node)
{
if (node == NULL)
return;
else
{
bst_traverseInOrderNode(node->left);
printf("%d ", node->v);
bst_traverseInOrderNode(node->right);
}
}
特别是,似乎我必须重新分配t
到bst-insert(t, 5)
inmain
才能实际修改t
自身,因为 bst_insert 不采用 aBST *
引用,而只采用值(例如,它永远不能真正改变 aBST *
本身)。然而,稍后,当 BST 被创建时,我可以简单地声明bst_insert(t, 8)
,这将改变t
自己(例如 change t->root->left
),即使它没有t
通过引用作为参数接收。有人可以向我解释这里的区别吗?非常感谢!