gpt4 book ai didi

c++ - 这段二叉树代码会引起任何问题吗?

转载 作者:行者123 更新时间:2023-11-27 23:25:55 26 4
gpt4 key购买 nike

我写了一段代码,它在我的系统上运行良好。我没有任何问题,但我有一些担忧,我在下面列出。我想知道是否存在真正的问题。

# include <iostream>
# include <stdio.h>
# include<conio.h>
using namespace std;

struct tree
{
int data;
struct tree * left;
struct tree * right;
};

struct tree * insert(struct tree * root,int value)
{
if(root==NULL)
{
struct tree *node=(struct tree *)malloc(sizeof(struct tree));
node->data = value;
node->left=NULL;
node->right=NULL;
return node;
}
else if(root->data > value)
root->left=insert(root->left,value);
else {
root->right=insert(root->right,value);
/*return root;*/ // code works fine for me without this return
}
}

void display(struct tree * root)
{
if (root!=NULL)
{
display(root->left);
cout << "value is : " << root->data << " \n";
display(root->right);
}
}

int main()
{
struct tree* root=NULL;
root=insert(root,8);
insert(root,6);
insert(root,5);
insert(root,2);
insert(root,1);
insert(root,7);
insert(root,15);
display(root);
delete root;
getch();
}

我的代码在插入函数中没有 return root 语句的情况下工作正常。让我担心的是,在创建根和在此递归函数中插入最终元素之间的递归调用期间,我没有返回任何内容。但对我来说一切都还好。

在更复杂的编码场景中,这会成为 future 的问题吗?

最佳答案

这段代码工作正常,因为 insert 在创建新节点时返回一些东西,并将指向新节点的指针返回给它的父节点。没有必要将 parent 的指针返回给祖 parent ——祖 parent 已经有了 parent 的指针。所以插入是正确的。

还有一点需要注意:您的代码很容易发生内存泄漏。 main 中的语句 delete root; 不足以释放所有分配的内存。要删除所有 malloc 编辑的内存,您需要一个与 insert 非常相似的递归函数:当您将 node * 传递给它时, 该函数将首先释放 leftright child ,然后释放自己。就像二叉树的后序遍历。

关于c++ - 这段二叉树代码会引起任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9553632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com