E - 求二叉树的层次遍历

#include<bits/stdc++.h>
#define endl '\n'
#define INF 0x3f3f3f3f
using namespace std;
const int N=55;
string pre,mid;
int t,now,tot;
struct tree
{
    char dat;
    int l,r;
}tr[N];
int rebuild(int l,int r)
{
    if(l>r)return 0;
    int m;
    for(int i=l;i<=r;i++)
    {
        if(pre[now]==mid[i])
        {
            m=i;
            break;
        }
    }
    tr[++tot].dat=pre[now++];
    int root=tot;
    tr[root].l=rebuild(l,m-1);
    tr[root].r=rebuild(m+1,r);
    return root;
}
void floorprint(int root)
{
    queue<int> q;
    if(root)
        q.push(root);
    while(q.size())
    {
        int u=q.front();
        q.pop();
        cout<<tr[u].dat;
        if(tr[u].l)q.push(tr[u].l);
        if(tr[u].r)q.push(tr[u].r);
    }
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>pre>>mid;
        now=0;
        int root=rebuild(0,pre.size()-1);
        floorprint(root);
        cout<<endl;
    }
    return 0;
}
二叉树层次遍历算法可以通过队列来实现。首先将根节点入队,然后进入循环,循环条件为队列不为空。在循环中,首先将队首节点出队并访问该节点,然后将该节点的左子节点和右子节点(如果有)依次入队。重复这个过程直到队列为空。这样就可以按层次顺序遍历二叉树了。 以下是二叉树层次遍历算法的C代码示例: ```c #include <stdio.h> #include <stdlib.h> // 二叉树节点的结构定义 typedef struct BTnode { char element; struct BTnode *left; struct BTnode *right; } BTnode; // 层次遍历函数 void levelOrderTraversal(BTnode *root) { if (root == NULL) { return; } // 创建一个队列,并将根节点入队 BTnode *queue[100]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { // 出队并访问节点 BTnode *node = queue[front++]; printf("%c ", node->element); // 将左子节点和右子节点入队 if (node->left != NULL) { queue[rear++] = node->left; } if (node->right != NULL) { queue[rear++] = node->right; } } } int main() { // 创建一个二叉树(示例) BTnode *root = (BTnode*)malloc(sizeof(BTnode)); BTnode *node1 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node2 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node3 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node4 = (BTnode*)malloc(sizeof(BTnode)); root->element = 'A'; node1->element = 'B'; node2->element = 'C'; node3->element = 'D'; node4->element = 'E'; root->left = node1; root->right = node2; node1->left = node3; node1->right = NULL; node2->left = NULL; node2->right = node4; node3->left = NULL; node3->right = NULL; node4->left = NULL; node4->right = NULL; // 层次遍历二叉树 levelOrderTraversal(root); return 0; } ``` 以上是二叉树层次遍历算法的C代码实现。你可以根据需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值