【问题描述】二叉树按照二叉链表的方式存储。编写程序,计算二叉树中叶子结点的数目并输出;编写程序,将二叉树的每个结点的左、右子树进行交换,请注意不是只交换结点的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);
}