4. 二叉树左右子树交换操作

【问题描述】二叉树按照二叉链表的方式存储。编写程序,计算二叉树中叶子结点的数目并输出;编写程序,将二叉树的每个结点的左、右子树进行交换,请注意不是只交换结点的data值,而是左、右孩子指针指向的交换,最后输出交换后的二叉树的后序遍历序列。

【输入形式】二叉树的前序遍历序列,空指针的位置输入字符#

【输出形式】叶子结点的数目;左右子树交换后,后序遍历的序列,空子树的位置输出字符#

【样例输入】

ABE##F##CG###

【样例输出】

3

###GC##F##EBA

#include <iostream>
using namespace std;
#include <cstring>
struct node
{
    char data;
    node *lchild;
    node *rchild;
};
char a[100];
node *build(int len, int &i)
{
    if (i < len && a[i] != '#')
    {
        node *r = new node;
        r->data = a[i];
        r->lchild = build(len, ++i);
        r->rchild = build(len, ++i);
        return r;
    }
    else
        return NULL;
}
void exchange(node *t)
{
    if (t == NULL)
        return;
    node *r = new node;
    exchange(t->lchild);
    exchange(t->rchild);
    r = t->lchild;
    t->lchild = t->rchild;
    t->rchild = r;
}
void h(node *root)
{
    if (root)
    {
        h(root->lchild);
        h(root->rchild);
        cout << root->data;
    }
    else
        cout << "#";
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> a;
    int count = 0;
    for (int i = 0; i < strlen(a) - 2; i++)
    {
        if (a[i] != '#' && a[i + 1] == '#' && a[i + 2] == '#')
            count++;
    }
    cout << count << endl;
    int i = 0;
    node *r = build(strlen(a), i);
    exchange(r);
    h(r);
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wrong Ansewer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值