关闭

二叉树------层序遍历

标签: 二叉树
42人阅读 评论(0) 收藏 举报
分类:

题目描述:
给定一棵二叉树,要求从上到下按层输出。(每一层按从左到右的顺序)
思路:
按照按层创建二叉树的方法,使用一个队列。先将根节点入队,然后每次从队中取出队首元素,并将其左右子节点入队,持续此过程知道队列为空。(NULL不入队)

#include <iostream>
#include <deque>
#include <stdio.h>
using namespace std;
#define N 100
struct Node 
{
    char data;
    struct Node *left, *right;
};

struct SeQueue
{
    struct Node *addr[N];
    int front;
    int end;
};

Node *MakeTree();
void DisplayTree(Node *tree);
void PrintTreeByFloor(Node *tree);
void DeleteTree(Node **tree);

int main()
{
    Node *myTree = MakeTree();

    cout << "MidOrder: " << endl;
    DisplayTree(myTree);
    cout << endl;

    cout << "print tree by floor: " << endl;
    PrintTreeByFloor(myTree);
    cout << endl;

    DeleteTree(&myTree);
    return 0;
}

Node *MakeTree()
{
    char ch;
    SeQueue Q;
    SeQueue *q = &Q;
    q->front = 1;
    q->end = 0;
    Node *tmp = NULL;
    Node *root = NULL;

    cout << "Input some chars to make a tree(less than 99 and end by '@'):" << endl;
    ch = getchar();
    while(ch != '@' && ch != '\n')
    {
        tmp = new Node();
        tmp->data = ch;
        tmp->left = tem->right = NULL;
        q->end += 1;
        q->addr[q->end] = tmp;
        if(root = NULL)
        {
            root = tmp;
        }
        else
        {
            if(q->addr[q->front] != NULL)
            {
                if(q->end % 2 == 0)
                    q->addr[q->front]->left = tmp;
                else
                    q->addr[q->front]->right = tmp;
            }
            if(q->end % 2 != 0)
                q->front += 1;
        }
        ch = getchar();
    }
    return root;
}

void DisplayTree(Node *tree)
{
    Node *p = tree;
    if(p)
    {
        DisplayTree(p->left);
        cout << p->data << " ";
        DisplayTree(p->right);
    }
}

void PrintTreeByFloor(Node *tree)
{
    if(tree == NULL)
        return ;
    deque<Node *> treeNode;
    treeNode.push_back(tree);

    while(treeNode.size())
    {
        Node *tmp = treeNode.front();
        treeNode.pop_front();
        cout << tmp->data << " ";
        if(tmp->left)
            treeNode.push_back(tmp->left);
        if(tmp->right)
            treeNode.push_back(tmp->right);
    }
}

void DeleteTree(Node **tree)
{
    if(tree == NULL)
        return ;
    Node *p = *tree;
    if(p)
    {
        DeleteTree(&p->left);
        DeleteTree(&p->right);
        delete [] p;
    }
    *tree = NULL;
}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5786次
    • 积分:573
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条