【id:179】【5分】D. DS二叉树--层次遍历

题目描述

层次遍历二叉树,是从根结点开始遍历,按层次次序“自上而下,从左至右”访问树中的各结点。

建树方法采用“先序遍历+空树用0表示”的方法

建议使用队列结构实现,算法框架如下:

定义一个空白队列和一个树结点指针p

设T是指向根结点的指针变量,若二叉树为空,则返回;否则,令p=T,p入队,执行以下循环:

(1)队首元素出队到p;

(2)访问p所指向的结点; 

(3)p所指向的结点的左、右子结点依次入队。

(4)跳转步骤1循环,直到队列空为止

例如把上述算法中的访问操作定义为输出,算法结果就是把二叉树按层次遍历输出

输入

第一行输入一个整数t,表示有t个测试数据

第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行

输出

逐行输出每个二叉树的层次遍历结果

AC代码:
 

#include <iostream>
#include <queue>
//#include "math.h"
#include "algorithm"
#include "stack"
#include "iomanip"
using namespace std;
int mmax=1000;
queue<char> child;
queue<char> parents;


class node{
public:
    char data;
    node *left= nullptr;
    node *right= nullptr;
    node *parent = nullptr;
};
queue<node*> q;
node* Create(string str,int& index){
    if(str[index]=='0'){
        return nullptr;
    }
    node* tmp=new node;
    tmp->data=str[index];
    tmp->left= Create(str,++index);
    tmp->right= Create(str,++index);
    if(tmp->left)
        tmp->left->parent=tmp;
    if(tmp->right)
        tmp->right->parent=tmp;
    return tmp;
}


void cengci(node *root){
    if(!root)
        return;
    while(!q.empty()){
        if(root->left)
            q.push(root->left);
        if(root->right)
            q.push(root->right);
        cout<<q.front()->data;
        q.pop();
        cengci(q.front());
    }
    ;
}

int main() {
    int t;
    cin>>t;
    while(t--){
        string str;
        cin>>str;
        int index=0;
        node* root = Create(str,index);
        q.push(root);
        cengci(root);
        while (!q.empty()){
            cout<<q.front();
            q.pop();
        }
        cout<<endl;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值