简体   繁体   English

在屏幕上打印整个二叉树

[英]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. 我想将数字存储在二叉树中,以0退出,然后以升序输出数字。 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. 第一个插入函数是按值传递指针,因此从未修改过root。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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