2014-02-26 62 views
0

我是C新手,我正在学习函数和指针。我必须在t_print方法中以下面必需的格式打印二进制搜索树,我将非常感激一些人可以指导我如何去做。打印BST - C程序

我有这样的代码至今:

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*)){ 
} 

回答

0

这取决于您要在其中数据印刷的顺序,但“为了”一个BST,是合适的(相对于预购或后顺序)。

以“为了”打印树,该函数:

  • 如果当前节点不为空
    • 打印左子树为了
    • 打印当前节点
    • 打印右子树为了

“按顺序打印xxx子树”操作是使用左指针或右指针递归调用“按顺序打印”功能。

预购的算法是:

  • 如果当前节点不为空
    • 打印当前节点
    • 打印左子树预购
    • 打印正确的子树在预购

为后序的算法是:

  • 如果当前节点不为空
    • 打印左子树后序
    • 打印右子树后,为了
    • 打印当前节点

它真的就是这么简单。

好了,几乎就这么简单......

如果你想括号中的数据或以其他方式能够识别树状结构,你有工作有点困难。您通常最终还会添加一个封面函数,该函数会添加一个前缀(标识输出的标记)和一个后缀(可能只是一个换行符);这通常不是递归打印的一部分。但算法的核心与描述一样简单。

+0

我应该按给出的t_print()方法的格式打印树。 – user3267967

+0

好的;这是一个预订打印 - 您打印节点,然后打印它的子节点。您还需要将级别参数传递给打印函数,以便在节点之前打印正确数量的空格。真的很简单,只要你知道如何通过函数指针调用一个函数。既然你不能告诉打印函数指针要缩进多少个空格,你可能需要自己编写这些代码。 –

+0

它看起来像你正在编码的规范;你的老师是否会提供调用你的代码和打印函数的'main()'程序? –