簡體   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