简体   繁体   中英

printing whole binary tree on screen

I want to store numbers in a binary tree, exit with 0, then output the numbers in ascending order. Most answers I've seen were on searching in the tree, and the few that were covering this exact topic used methods that I didn't understand. I believe the tree itself is created correctly, but the output function is at fault. Where did I go wrong?

#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;
}

There were multiple mistakes. First insert function was passing pointer by value so root was never modified.

Also corrected output function.

#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;
}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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