簡體   English   中英

在屏幕上打印整個二叉樹

[英]printing whole binary tree on screen

我想將數字存儲在二叉樹中,以0退出,然后以升序輸出數字。 我看到的大多數答案都是在樹上搜索,而涉及此確切主題的少數答案則使用了我不了解的方法。 我相信樹本身是正確創建的,但是輸出功能有問題。 我哪里做錯了?

#include <iostream>
#include <stdio.h>
using namespace std;

struct thing {
    short num;
    short howmany = 0;
    thing* right;
    thing* left;
};

void insert(thing* akt, short x) {
    if (akt == NULL) {
        akt = new thing;
        akt->left = NULL;
        akt->right = NULL;
        akt->num = x;
        akt->howmany++;
    }
    else if (akt->num == x) akt->howmany++;
    else if (akt->num > x) return insert(akt->right, x);
    else return insert(akt->left, x);
}

void output(thing* root) {
    thing* akt;
    do {
        akt = root;
        while(akt->left!=NULL) akt=akt->left;
        if(akt->right!=NULL) return output(akt->right);
        cout << akt->num << " " << akt->howmany << "times\n";
        akt = NULL;
    } while (root != NULL);
}

int main() {
    thing* root = new thing;
    short x;
    cout << "number: ";
    cin >> x;
    do {
        insert(root, x);
        cout << "number: ";
        cin >> x;
    } while (x != 0);
    cout << endl;
    output(root);
    return 0;
}

有多個錯誤。 第一個插入函數是按值傳遞指針,因此從未修改過root。

還糾正了輸出功能。

#include <iostream>
#include <stdio.h>
using namespace std;

struct thing {
    short num;
    short howmany = 0;
    thing* right;
    thing* left;
};

void insert(thing* &akt, short x) {
    if (akt == NULL) {
        akt = new thing;
        akt->left = NULL;
        akt->right = NULL;
        akt->num = x;
        akt->howmany++;
    }
    else if (akt->num == x) akt->howmany++;
    else if (akt->num > x) return insert(akt->left, x);
    else return insert(akt->right, x);
}

void output(thing* root) {
    thing* akt = root;
    if(akt == NULL)
        return;

    output(akt->left);
    cout << akt->num << " " << akt->howmany << " times\n";
    output(akt->right);
}

int main() {
    thing* root = NULL;
    short x;
    cout << "number: ";
    cin >> x;
    do {
        insert(root, x);
        cout << "number: ";
        cin >> x;
    } while (x != 0);
    cout << endl;
    output(root);
    return 0;
}`

暫無
暫無

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

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