数据结构练习题――中序遍历二叉树时间限制(普通/Java):1000MS/10000MS 内存限制:65536KByte
二叉树经典题,思路是运用结构体和指针结合,用指针指向左右俩元素值输入并输出。输出时运用了dfs的思想。 accode: |
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[1005];
int cnt = 1;
struct tree {
int data;
tree* l, * r;
};
void creattree(tree* &T, int x) //创建树 as*是树,&是为了改变T的值
{
if (a[x] == 0)
{
T = NULL;
return;
}
T = (tree*)malloc(sizeof (tree));
T->data = a[x];
creattree(T->l, 2 * x);
creattree(T->r, 2 * x + 1);
}
int findhigh(int ncnt)
{
int s = 1;
int ceng = 0;
ncnt--; //最后多加了一个减掉
while (ncnt - s >= 0)
{
ncnt -= s;
s *= 2;
ceng++;
}
if (ncnt > 0)ceng++;
return ceng;
}
void findanswer(tree* T)
{
if (T)
{
findanswer(T->l); //中序遍历运用递推
cout << " " << T->data;
findanswer(T->r);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
tree* T;
T = NULL;
while (n--)
{
int x;
cnt = 1; //sizeof a可能错
memset(a, 0, sizeof (a)); //一定要加括号!部分oj平台不加括号可能ce
while (cin >> x, x != -1)
{
a[cnt++] = x;
}
int ceng = findhigh(cnt);
creattree(T, 1);
cout << ceng;
findanswer(T);
cout << "\n";
}
return 0;
}