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

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容