我是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*) ){
}
答案 0 :(得分:0)
这取决于您希望打印数据的顺序,但对于BST,“按顺序”是合适的(与预订或后订购相反)。
要按顺序打印树,该功能可以:
'按顺序打印xxx子树'操作是使用左或右指针递归调用'print in order'函数。
预购的算法是:
后期订购的算法是:
这真的很简单。
嗯,差不多那么简单......
如果要包括数据或以其他方式识别树结构,则必须更加努力。您通常最终会得到一个封面功能,它会添加前缀(标识输出的标签)和后缀(可能只是换行符);这通常不是递归打印的一部分。但算法的核心与描述的一样简单。