繁体   English   中英

打印BST-C程序

[英]printing BST - C Program

我是C语言的新手,正在学习函数和指针。 我必须在t_print方法中以下面的必需格式打印Binary搜索树,我真的很感谢一些可以指导我如何做的事情。

到目前为止,我有以下代码:

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,“按顺序”是合适的(与预订购或后订购相反)。

要“按顺序”打印树,该函数将执行以下操作:

  • 如果当前节点不为空
    • 按顺序打印左子树
    • 打印当前节点
    • 按顺序打印正确的子树

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

预订算法为:

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

下订单的算法为:

  • 如果当前节点不为空
    • 以后顺序打印左子树
    • 按后顺序打印正确的子树
    • 打印当前节点

真的就是这么简单。

好吧,几乎就是这么简单...

如果您想将数据放在方括号中,或者以其他方式可以识别树结构,则必须加倍努力。 通常,您通常还会得到一个覆盖函数,该函数添加一个前缀(标识输出的标签)和一个后缀(可能只是换行符); 通常,这不是递归打印的一部分。 但是算法的核心很简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM