我正在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);
}
感谢任何帮助:)
提前致谢
答案 0 :(得分:0)
确定它,现在运行正常
这里是代码
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);}
}