簡體   English   中英

在Turbo C中以樹格式打印BST

[英]printing a BST in a tree format in turbo c

我想以樹格式打印BST的內容,例如:

我當前的打印輸出:

10-> 20-> 30-> 40-> 60-> 80-> 90->

我想要它是什么樣的:

        40
        /\
       /  \
     20    60
     / \    \
   10  30   80
              \
              90

我試着做些gotoxy,但是由於某種原因,我無法像樹一樣打印出來,我想我需要做的不只是gotoxy。 同樣,“ \\”並不是真正必需的,只是一個附加功能,不會使任何人感到困惑。

守則如下:

結構體:

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

打印:

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    if (t->l != NULL)    
        inorder(t->l);
        printf("%d -> ", t->value);
    if (t->r != NULL)    
        inorder(t->r);
}

我在樹打印中的嘗試:

void print(struct btnode *t, int x, int i, int y)
{
    i = i / 2 + 2;
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }

    if (t->l != NULL){
        print(t->l, (x + i), i, (y + 1));
    }

    if (t->r != NULL){
        print(t->r, (x + i), i, (y + 1));
    }
    gotoxy(x, y * 2);
    printf("%d -> ", t->value);
}

關於如何可以基於當前輸出代碼實現樹輸出的任何想法,盡管我認為如果要把樹變成樹,還需要做更多的工作。 任何事情都會有所幫助,一個指南或一個想法將不勝感激。

謝謝

棘手的問題。 首先讓我們看一個更簡單的問題:如何水平打印樹,使樹的根向左,分支向右生長。 通過跟蹤縮進級別,可以在不將光標定位在控制台窗口中的情況下完成此操作:

void horizontal(struct btnode *t, int level)
{
    int l = level;

    if (t == NULL) return;

    horizontal(t->l, level + 1);
    while (l--) printf("    ");
    printf("-> %d\n", t->value);
    horizontal(t->r, level + 1);
}

從上到下打印樹是相似的。 縮進現在是從頂部開始的位置。 棘手的部分是如何使打印前進到右邊。 在簡單的控制台示例中,這是通過打印新行來完成的。 在這里,我們必須前進x位置。 這可以使用全局變量x來完成,但是您也可以將狀態保留在print函數中指向的變量中:

void print(struct btnode *nd, int *x, int y)
{    
    if (nd == NULL) return;

    print(nd->l, x, y + 4);
    gotoxy(*x, y);
    printf("%d", nd->value);
    *x += 4;
    print(nd->r, x, y + 4);
}

像這樣調用print函數:

int x = 0;
print(root, &x, 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM