#include <cassert> #include <cmath> #include <iostream> #include <queue> using namespace std; class Node{ public: //值 int data; //左孩子 Node* leftCh; //右孩子 Node* rightCh; //所在层 int level; Node(int data, Node* leftCh, Node* rightCh,int level) { this->data = data; this->leftCh = leftCh; this->rightCh = rightCh; this->level=level; } }; int* array; int n; /***先序建树 * */ Node* buildNode(int index,int level){ if(index>=n){ return NULL; }else{ Node* p=new Node(array[index], NULL, NULL,level); //递归左子树 p->leftCh=buildNode((index<<1)+1,level+1); //递归右子树 p->rightCh=buildNode((index<<1)+2,level+1); return p; } } void buildTree(int height){ n=(int)pow(2, height)-1; array=new int[n]; for(int i=0;i<n;i++){ array[i]=i+1; } Node* root=buildNode(0,1); queue <Node*> que; que.push(root); int index=0; int level=1; //层序输出 while(!que.empty()){ Node* p=que.front(); que.pop(); //断言顺序表、二叉链表对应的节点相等 assert(p->data==array[index]); if(p->level>level){ cout<<endl; level++; } cout<<p->data<<" "; index++; if(p->leftCh!=NULL){ que.push(p->leftCh); } if(p->rightCh!=NULL){ que.push(p->rightCh); } } cout<<endl; } int main(int argc, char **argv) { buildTree(4); return 0; }