jishan7.github.io

按行打印二叉树,每行后面回车

C++代码:

#include <iostream>
#include <queue>
using namespace std;

struct Node
{
    Node *left;
    Node *right;
    char data;
};

/* 初始化一棵树 */
Node *initTree()
{
    Node *root = new Node;
    Node *b = new Node;
    Node *c = new Node;
    Node *d = new Node;
    Node *e = new Node;
    Node *f = new Node;

    root->data = 'a';
    c->data = 'c';
    b->data = 'b';
    d->data = 'd';
    e->data = 'e';
    f->data = 'f';

    root->left = b;
    root->right = c;
    b->left = d;
    b->right = e;
    c->right = f;
    c->left = NULL;

    d->left = e->left = f->left = NULL;
    d->right = e->right = f->right = NULL;

    return root;
}

void printTreebyRow(Node *root)
{
    queue<Node *> storequeue;
    storequeue.push(root);
    while (!storequeue.empty())
    {
        int rowcount = 0;
        queue<Node *> showqueue(storequeue);
        while (!showqueue.empty())
        {
            cout << showqueue.front()->data;
            showqueue.pop();
            ++rowcount;
        }
        cout << endl; // 回车

            while (rowcount)
        {
            if (storequeue.front()->left)
                storequeue.push(storequeue.front()->left);
            if (storequeue.front()->right)
                storequeue.push(storequeue.front()->right);
            storequeue.pop();
            --rowcount;
        }
    }
}

int main()
{
    printTreebyRow(initTree());

    return 0;
}