二叉树层次遍历-按层换行

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

struct Node
{
    int val;
    Node *lc;
    Node *rc;
};

void create(Node *&head)
{
    head = (Node*)malloc(sizeof(Node)); head->val = 1;
    
    head->lc = (Node*)malloc(sizeof(Node)); head->lc->val=2;
    head->rc = (Node*)malloc(sizeof(Node)); head->rc->val=3;
    
    head->lc->lc =(Node*)malloc(sizeof(Node)); head->lc->lc->val =4;
    head->lc->rc =(Node*)malloc(sizeof(Node)); head->lc->rc->val =5;
    head->rc->lc =(Node*)malloc(sizeof(Node)); head->rc->lc->val =6;
    head->rc->rc =(Node*)malloc(sizeof(Node)); head->rc->rc->val =7;
    
    head->lc->lc->lc= NULL;
    head->lc->lc->rc= NULL;
    head->lc->rc->lc= NULL;
    head->lc->rc->rc= NULL;
    head->rc->lc->lc= NULL;
    head->rc->lc->rc= NULL;
    head->rc->rc->lc= NULL;
    head->rc->rc->rc= NULL;
}

void myprint(Node *head)
{
    queue<Node*>q;
    int last,nlast;
    
    if(head!=NULL) 
    {
        last=head->val;
        q.push(head);
        nlast = head->val;
    }
    
    while(!q.empty())
    {
        Node *tmp;
        tmp = q.front();
        cout<<tmp->val<<" ";
        q.pop();
        if(tmp->lc!=NULL) 
        {
            q.push(tmp->lc);
            nlast=tmp->lc->val; 
        }
        if(tmp->rc!=NULL) 
        {
            q.push(tmp->rc);
            nlast=tmp->rc->val; 
        }
        if(last == tmp->val)
        {
            cout<<endl; 
            last = nlast;
        }
    }
}

int main()
{
    Node *head;
    create(head);
    myprint(head);
    return 0;
}
    原文作者:写代码不如跳舞
    原文地址: https://www.jianshu.com/p/b590c343448d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞