(附加实验)二叉树的建立和输出

这篇博客介绍了如何通过二叉树的中序和后序遍历序列来构建二叉树,并实现分层输出。首先,算法根据给定的节点数量、中序和后序序列创建二叉树。接着,当二叉树不为空时,程序将分层打印二叉树的所有节点,每一层占一行,输出类似于'Level 1:'的层次信息。
摘要由CSDN通过智能技术生成

问题描述:

假设二叉树的元素为字符,采用二叉链式存储。请编写算法完成:
(1)已知二叉树的中序和后序遍历序列,创建二叉树;
(2)实现二叉树的分层输出;
输入有三行:
第一行,一个整数n,是二叉树中的元素(结点)个数;
第二行,二叉树的中序遍历序列
第三行,二叉树的后序遍历序列
输出:
如果二叉树为空,则输出“Binary tree is empty!”
如果二叉树不空,则二叉树有几层则输出几行:
Level 1:
Level 2:

例如:

输入Result
9
HBDFAEKCG
HDFBKGCEA
Level 1:A
Level 2:BE
Level 3:HFC
Level 4:DKG

答案:

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

typedef struct BinTreeNode{
    struct BinTreeNode *leftChild,*rightChild;
    char data;
    int level;
}BNode,*BTree;

BTree CreateBinTree2(char *LRV,char *LVR,int n){
    if (n<=0) return NULL;
    int k = 0;
    while (LRV[n-1]!=LVR[k]) k++;
    BTree temp = new BNode();
    temp->data = LRV[n-1];
    temp->leftChild = CreateBinTree2(LRV,LVR,k);
    temp->rightChild = CreateBinTree2(LRV+k,LVR+k+1,n-k-1);
    return temp;
}

void LevelOrder(BTree subTree){
    int l = 1;
    if(subTree==NULL){
        cout<<"Binary tree is empty!"<<endl;
        return;
    }
    queue<BTree>q;
    BTree p = subTree;
    p->level = 1;
    q.push(p);
    while(!q.empty()){
        p = q.front();
        q.pop();
        if(p->level==l){
            if(l!=1) cout<<endl;
            cout<<"Level "<<p->level<<':';
            l++;
        }
        cout<<p->data;
        if(p->leftChild!=NULL){
            p->leftChild->level = p->level+1;
            q.push(p->leftChild);
        }
        if(p->rightChild!=NULL){
            p->rightChild->level = p->level+1;
            q.push(p->rightChild);
        }
    }
}

int main() {
    BTree Tree;
    int n;
    char in[100],post[100];
    cin>>n;
    cin>>in;
    cin>>post;
    Tree=CreateBinTree2(post,in,n);
    LevelOrder(Tree);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值