#include
#include
#include<stdlib.h>
#include<time.h>
#include
#include
using namespace std;
typedef struct node* tree;
struct node
{
long int data;
node* left;
node* right;
};
tree buildtree1()//普通建树,就是根据已知将各个位置填写
{
tree root = new node;
root->data = 1;
root->left = new node;
root->right = new node;
root->left->data = 2;
root->right->data = 3;
return root;
}
tree buildtree2(tree root)//先序建树,以左边为先序,先输入左边的
{
int c;
cin >> c;
if (c == -1)
{
return NULL;
}
root->data = c;
root->left = NULL;
root->right = NULL;
buildtree2(root->left);
buildtree2(root->right);
return root;
}
tree buildtree3(int a[], int n)//完美二叉树建立
{
tree root = new node[n+1];
//tree root = (tree)malloc(sizeof(node) * (n + 2));
for (int i=1; i <= n; i++)
{
root[i].data = a[i];
root[i].left = NULL;
root[i].right = NULL;
}
for (int i = 1; i <= n / 2; i++)
{
if(2*i<=n)
root[i].left = &root[i * 2];
if((2*i+1)<=n)
root[i].right = &root[i * 2 + 1];
}
return &root[1];
}
void cengxu(tree root)//层序遍历
{
queueque;
if (root == NULL)
{
return;
}
que.push(root);
while (!que.empty())
{
cout << que.front()->data << " ";
if (que.front()->left) que.push(que.front()->left);
if (que.front()->right)que.push(que.front()->right);
que.pop();
}
}
int main()
{
int a[11] = { 0,1,2,3,4,5,6,7,8,9,10 };
tree root=buildtree3(a, 10);
cengxu(root);
}