我大约在 2 年前完成了一些课程作业...
我创建了一个节点结构,其中包含自己的数据和 2 个节点,一个左一个右,它看起来像这样(我找不到最终代码,可能使用了共享指针):
struct node
{
int data;
node *left;
node *right;
};
然后我通过使用递归向其添加更多节点来创建我的树,如下所示:
void insert(node **tree, int value)
{
if (*tree == nullptr)
{
*tree = new node;
(*tree)->data = value;
(*tree)->left = nullptr;
(*tree)->right = nullptr;
}
else if (value < (*tree)->data)
{
insert(&((*tree)->left), value);//memory location of the pointer to the node of the node
}
else if (value > (*tree)->data)
{
insert(&((*tree)->right), value);
}
else
return;
}
旁注:回首往事,如果可能的话,我从未考虑过添加与现有节点具有相同值的节点。
我假设你会做类似的事情。现在来回答你的问题,打印出来,也使用递归。
void inorder(node *tree)
{
if (!(tree == nullptr))
{
inorder((tree)->left);
cout << (tree->data) << endl;//Prints on new lines, you could comma separate them if you really wanted.
inorder((tree)->right);
}
}
最后,您需要在使用完树后清理它,因此您需要将其删除...递归。
说实话已经有一段时间了,这个递归的东西对我来说仍然有点困惑,所以我可能忘记了一些东西,但理论就在那里!
编辑,使用的标题:<iostream> 和 <memory>,这也是 c++ 而不是 c,但它们非常相似。