【问题描述】求解二叉树的宽度,请用递归和非递归两种方法求解。
【输入形式】前序和中序序列建树
【输出形式】递归和非递归求解的宽度值
【样例输入】
abcdefg
cbdaegf
【样例输出】
3 3
#include <iostream>
using namespace std;
#include <cstring>
#include <queue>
struct node
{
char data;
node *lchild;
node *rchild;
};
int height = 0;
int width[1000];
char mid[1001], pre[1001];
node *build(int x, int y, int q, int p) // xy为前序序列的左右边界,qp为前序序列的左右边界
{
int i;
if (x > y || q > p)
return NULL;
node *root = new node;
root->data = pre[x];
root->lchild = NULL;
root->rchild = NULL;
for (i = q; i <= p; i++)
if (pre[x] == mid[i])
break;
root->lchild = build(x + 1, x + i - q, q, i - 1);
root->rchild = build(x + i - q + 1, y, i + 1, p);
return root;
}
void get_height(node *root, int step = 1)
{
if (root == NULL)
return;
height = max(step, height);
get_height(root->lchild, step + 1);
get_height(root->rchild, step + 1);
}
void store_wild(node *root, int i) //递归方法
{
if (root != NULL)
{
width[i]++;
// cout << i << " " << width[i] << endl;
store_wild(root->lchild, i + 1);
store_wild(root->rchild, i + 1);
}
}
int get_width1(node *root)
{
get_height(root, 1);
for (int i = 0; i < height; i++)
width[i] = 0;
store_wild(root, 0);
// for (int i = 0; i < height; i++)
// cout << width[i];
int maxx = 0;
for (int i = 0; i < height; i++)
maxx = max(maxx, width[i]);
return maxx;
}
int get_width2(node *root)
{
queue<node *> q;
node *p = root;
q.push(p);
int maxx = 0;
while (!q.empty())
{
int flag = 0;
int len = q.size();
while (flag < len)
{
flag++;
p = q.front();
q.pop();
if (p->lchild)
q.push(p->lchild);
if (p->rchild)
q.push(p->rchild);
}
maxx = max(maxx, len);
}
return maxx;
}
int main()
{
cin >> pre >> mid;
int len = strlen(mid);
node *root;
root = build(0, len - 1, 0, len - 1);
cout << get_width1(root) << " " << get_width2(root);
return 0;
}