打印BST-C程序



我是C的新手,正在学习函数和指针。我必须在t_print方法中以下面必要的格式打印二进制搜索树,我真的很感激有人能指导我如何进行。

我现在有这个代码:

typedef struct tree {
void* data;
struct tree* left;
struct tree* right;
} Tree;

/*set the data on the tree node */
void  t_set_data(Tree* t, void* data) {
t->data = data;}
/*let l be the left node of tree *t */
void  t_set_left(Tree* t, Tree* l){
t->left = l;}
/*let r be the left node of tree *t */
void  t_set_right(Tree* t, Tree* r){
t->right = r;}
/* simply return left node of the tree */
Tree* t_left(Tree* t){
return t-> left;}
/* simply return right node of the tree */
Tree* t_right(Tree* t){
return t-> right;}
/* simply return the data of the tree */
void* t_data(Tree* t){
return t->data;}
/* make the node of the tree and allocate space for it*/
Tree* t_make(){
Tree *t = (Tree*)malloc(sizeof(tree));
t->left=NULL;
t->right = NULL;
t-> data = NULL;
return t;
}
/* 
print the whole tree in the following format
Root is printed with zero trailing spaces to the left
Every node/subtree is printed with one additional space
Below is an example for a tree with depth 2:
Root
<space>Left-Child
<space><space>Left-Left-Child
<space><space>Left-Right-Child
<space>Right-Child 
.... and so on ...

Use (void(* p))(function pointer) to print.
*/
void  t_print( Tree* t ,int space, void(* p)(void*) ){
}

这取决于您希望打印数据的顺序,但对于BST,"按顺序"是合适的(与预购或后购相反)。

要"按顺序"打印树,函数会执行以下操作:

  • 如果当前节点不是null
    • 按顺序打印左侧子树
    • 打印当前节点
    • 按顺序打印右侧子树

"按顺序打印xxx子树"操作是使用左指针或右指针对"按顺序进行打印"函数的递归调用。

预购的算法是:

  • 如果当前节点不是null
    • 打印当前节点
    • 按预购顺序打印左侧子树
    • 按预购顺序打印右侧子树

后订单的算法是:

  • 如果当前节点不是null
    • 按后期顺序打印左侧子树
    • 按过帐顺序打印右侧子树
    • 打印当前节点

就这么简单。

好吧,几乎就这么简单。。。

如果你想把数据括起来,或者以其他方式使识别树结构成为可能,你必须更加努力。您通常还会得到一个cover函数,它添加了一个前缀(标识输出的标签)和一个后缀(可能只是一个换行符);这通常不是递归打印的一部分。但该算法的核心正如所描述的那样简单。

最新更新