首页 > 代码库 > 【编程之美】3.10分层遍历二叉树

【编程之美】3.10分层遍历二叉树

主要难度在于何时插入换行

学习到的:①vector 可以像数组一样用 不一定要用迭代器

 

代码及注释如下:

#include<iostream>#include<queue>using namespace std;typedef struct BiTree{    BiTree * pLeft, * pRight;    int data;}BiTree;void createBiTree(BiTree * &T){    int d;    cout << "please input the data of tree:";    cin >> d;    if(d != 0)    {        T = new BiTree;        T->data =http://www.mamicode.com/ d;        T->pLeft = NULL;        T->pRight = NULL;        createBiTree(T->pLeft);        createBiTree(T->pRight);    }}//分层打印整个二叉树 答案的思路 用游标cur last标示回车位置 不用辅助结点void PrintNodeByLevel(BiTree* root){    if(root == NULL)    {        return;    }    vector<BiTree *> vec;    vec.push_back(root);    int cur = 0;    int last = 1;    while(cur < vec.size())    {        last = vec.size(); //新一行访问开始 重定位last于当前行最后一个结点的下一个结点        while(cur < last)        {            printf("%d ", vec[cur]->data); //注意 vector也可以像数组一样用            if(vec[cur]->pLeft != NULL)            {                vec.push_back(vec[cur]->pLeft);            }            if(vec[cur]->pRight != NULL)            {                vec.push_back(vec[cur]->pRight);            }            cur++;        }        printf("\n");    }}//分层打印整个二叉树 我自己的思路 利用数据为‘\n’的辅助的树节点标示回车位置void Travese(BiTree * T){    queue<BiTree *> Q;    BiTree Assist;    Assist.data = \n;  //辅助表示回车    Assist.pLeft = NULL;    Assist.pRight = NULL;    Q.push(T);    Q.push(&Assist);    while(!Q.empty())    {        BiTree * TmpTree = Q.front();        Q.pop();        if(TmpTree->data != \n)        {            if(TmpTree->pLeft != NULL) //注意  空指针不压入 因为下面还要判断其下一个有效树结点是不是回车            {                Q.push(TmpTree->pLeft);            }            if(TmpTree->pRight != NULL)            {                Q.push(TmpTree->pRight);            }            if(Q.front()->data =http://www.mamicode.com/= \n) //当一个\n要被弹出时 压入下一个\n            {                Q.push(&Assist);            }            printf("%d ", TmpTree->data);                    }        else if(TmpTree->data =http://www.mamicode.com/= \n)        {            printf("\n");        }    }}//打印二叉树中指定层的结点 根节点为第0层int PrintNodeAtLevel(BiTree* root, int level){    if(root == NULL || level < 0)    {        return 0;    }    if(level == 0)    {        printf("%d ", root->data);        return 1;    }    else    {        int returnl = 1, returnr = 1;        if(root->pLeft != NULL)        {            returnl = PrintNodeAtLevel(root->pLeft, level - 1);        }        if(root->pRight != NULL)        {            returnr = PrintNodeAtLevel(root->pRight, level - 1);        }        return (returnl && returnr) ? 1 : 0;    }}int main(){    BiTree * T = NULL;    createBiTree(T);    Travese(T);    PrintNodeAtLevel(T, 2);    printf("\n");    PrintNodeByLevel(T);    return 0;}

 

【编程之美】3.10分层遍历二叉树