首页 > 解决方案 > 在屏幕上打印整个二叉树

问题描述

我想将数字存储在二叉树中,以 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;
}

标签: c++tree

解决方案


有多个错误。第一个插入函数按值传递指针,因此从未修改过根。

还修正了输出功能。

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

推荐阅读