利用特殊的二叉树层序重构二叉树

如果直接利用二叉树的层序是没有办法构建一个二叉树的,但是如果是完全二叉树应该是可以的

这里层序序列中用-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));}} 还有前面介绍通过前序,后序,中序组合进行构建的方法,可参考

背着背包的路上,看过许多人,听过许多故事,

利用特殊的二叉树层序重构二叉树

相关文章:

你感兴趣的文章:

标签云: