如果直接利用二叉树的层序是没有办法构建一个二叉树的,但是如果是完全二叉树应该是可以的
这里层序序列中用-1表示当前节点没有值
构建主要采用了非递归的方法,利用了queue,因为层序的遍历可以通过queue来实现那么自然也可以通过这个方法进行构建
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef struct Tree
{
Tree * left;
Tree * right;
int data;
Tree()
{
data = -1;
left = NULL;
right = NULL;
}
}Tree;
void buildTree(int * A,int length,Tree * root)
{
if ((NULL == root) || (0 == length))
{
return;
}
queue<Tree*> s;
int i = 0;
root->data= A[0];
s.push(root);
i++;
while ((!s.empty()) && (i < length))
{
Tree* cur = s.front();
s.pop();
if ((A[i] != -1) && (i < length))
{
Tree * node = new Tree;
node->data = A[i];
cur->left = node;
s.push(node);
}
i++;
if ((A[i] != -1) && (i < length))
{
Tree * node = new Tree;
node->data = A[i];
cur->right = node;
s.push(node);
}
i++;
}
};
int main(void)
{
Tree *root=new Tree; //<定义一个根结点
int a[13]= {3,5,9,2,18,7,-1,-1,-1,9,19,-1,-1};
buildTree(a,13,root);
return 0;
} void CreateBiTree(BiTNode **root) //二级指针作为函数参数
{
char ch; //要插入的数据
scanf("\n%c", &ch);
//cin>>ch;
if(ch=='#')
*root = NULL;
else
{
*root = (BiTNode *)malloc(sizeof(BiTNode));
(*root)->data = ch;
printf("请输入%c的左孩子:",ch);
CreateBiTree(&((*root)->lchild));
printf("请输入%c的右孩子:",ch);
CreateBiTree(&((*root)->rchild));
}
} http://blog.csdn.net/xietingcandice/article/details/42557839
原文地址:http://blog.csdn.net/xietingcandice/article/details/43486849