gpt4 book ai didi

c - 使用指针在二叉树中进行深度优先搜索

转载 作者:行者123 更新时间:2023-11-30 21:11:21 25 4
gpt4 key购买 nike

我目前正在学习 C 中的指针算术作为练习,我想编写一个二叉树

到目前为止我已经得到了结构本身

typedef struct bintree
{ struct bintree *left;
struct bintree *right;
int value;
} bintree ;

树的构造

bintree *new_bintree (int value)
{ bintree *node = malloc(sizeof(bintree));
knoten -> left = NULL;
knoten -> right = NULL;
knoten -> value = value;
return (node);
}

添加节点功能

int bintree_add(bintree *tree, int value)
{ if (value == tree->value)
{return(-1);}
if ((value <= tree->value)&&(tree->left!=NULL)) /*Left node check and insert*/
{ return(bintree_add(tree->left, value));}
if ((value <= tree->value)&&(tree->left==NULL))
{bintree *knoten = malloc(sizeof(bintree));
knoten -> left = NULL;
knoten -> right = NULL;
knoten -> value = value;
tree -> left = node;
return(0);
}

if ((value >= tree->value)&&(tree->right!=NULL)) /*right node check and insert*/
{ return (bintree_add(tree->right, value));}
if ((value >=tree->value)&&(tree->right == NULL))
{bintree *knoten = malloc(sizeof(bintree));
knoten -> right = NULL;
knoten -> left = NULL;
knoten -> value = value;
tree -> right = node;
return (0);
}
}

和清除功能

void delete_bintree(bintree *tree)
{
if (tree->left != NULL)
{delete_bintree (tree->left);}
if (tree->right != NULL)
{delete_bintree (tree->right);}
free(tree);
}

现在我想实现 DepthFirstSearch 和 BreathFirstSearch

这是我迄今为止的 DFS 代码

bool bintree_dsearch(bintree *tree, int value)
{
if (value == tree->value)
{return true;}
if (tree->value == NULL)
{return false;}
if (tree->left != NULL)
{return bintree_dsearch(tree->left, value);}
else return bintree_dsearch(tree->right, value);

}

感谢任何帮助:)

提前致谢

最佳答案

确定已修复,现在运行良好

这是代码

bool bintree_dsearch(bintree *tree, int value)
{
if (value == tree->value)
{return true;}
if (tree->value == NULL)
{return false;}
if (tree->left != NULL)
{return bintree_dsearch(tree->left, value);}
if (tree->right != NULL)
{return bintree_dsearch(tree->right, value);}
}

关于c - 使用指针在二叉树中进行深度优先搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911298/

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