前序+中序 = 二叉树(先序、中序、后序、层次遍历)
内心OS:我靠啊!!!我就是偷了一下懒!!!把先序遍历的代码COPY了两份,改成了中序和后序遍历。万万没想到啊!我忘了修改函数中递归函数的名字!!!找这个BUG花了我三个小时~~我哭啊~~,我还以为我的知识体系坍塌了呢?!!~
总结,这是一道模板题,要先记住大体流程,然后反复练习。
输入格式:
第一行给出结点个数 N(1<=N<= 50)
第二行给出先序序列,共N个整数
第三行给出后序序列,共N个整数
输出格式:
第一行给出先序遍历结果;
第二行给出中序遍历结果;
第三行给出后续遍历结果;
第四行给出层次遍历结果。
输入样例:
7
4 1 3 2 6 5 7
1 2 3 4 5 6 7
输出样例:
4 1 3 2 6 5 7
1 2 3 4 5 6 7
2 3 1 5 7 6 4
4 1 6 3 5 7 2
1 #include<iostream> 2 #include<algorithm> 3 #include<queue> 4 using namespace std; 5 6 const int maxn = 100; 7 int pre[maxn],in[maxn];//先序、中序 8 int n; //结点个数 9 struct Node { 10 int data; 11 Node* lchild; 12 Node* rchild; 13 }; 14 15 //当前二叉树的 先序区间[preL,preR], 中序区间[inL,inR] 16 Node* create(int preL,int preR,int inL,int inR) { 17 //第一步,确定递归边界 18 if(inL > inR) return NULL; 19 //第二步,保存当前根结点 20 Node* root = new Node; 21 root->data = pre[preL]; 22 //第三步,用根结点划分中序,求出根节点左子树结点的个数 23 int k,leftNum; 24 for(k = inL; k <= inR; ++k) 25 if(in[k] == pre[preL]) break; 26 leftNum = k - inL; 27 //第四步,确定左子树的后序、中序, 右子树的后序,中序 28 root->lchild = create(preL+1,preL+leftNum,inL,k-1); 29 root->rchild = create(preL+leftNum+1,preR,k+1,inR); 30 return root; 31 } 32 33 int num = 0; //已经访问结点个数 34 //先序遍历二叉树 35 void preorder(Node* root) { 36 if(root == NULL) return ;//递归边界 37 if(num > 0) printf(" "); 38 cout<<root->data; 39 num++; 40 preorder(root->lchild);//访问左子树,两个选择分支 41 preorder(root->rchild);//访问右子树 42 } 43 //中序遍历二叉树 44 void inorder(Node* root) { 45 if(root == NULL) return ;//递归边界 46 inorder(root->lchild);//访问左子树,两个选择分支 47 if(num > 0) printf(" "); 48 cout<<root->data; 49 num++; 50 inorder(root->rchild);//访问右子树 51 } 52 //后序序遍历二叉树 53 void postorder(Node* root) { 54 if(root == NULL) return ;//递归边界 55 postorder(root->lchild);//访问左子树,两个选择分支 56 postorder(root->rchild);//访问右子树 57 if(num > 0) printf(" "); 58 cout<<root->data; 59 num++; 60 } 61 //层次遍历 62 void BFS(Node *root) { 63 queue<Node*> que;//第一步,定义队列,结点入队 64 que.push(root); 65 while(!que.empty()) { //第二步,队列非空 66 Node* top = que.front();//第三步,访问队头元素,并出队 67 que.pop(); 68 if(num > 0) printf(" "); 69 cout<<top->data; 70 num++; 71 //第四步,下一层元素入队(左、右孩子入队) 72 if(top->lchild != NULL) que.push(top->lchild); 73 if(top->rchild != NULL) que.push(top->rchild); 74 } 75 } 76 int main() { 77 cin>>n; 78 for(int i = 0; i < n; ++i) 79 cin>>pre[i]; 80 for(int i = 0; i < n; ++i) 81 cin>>in[i]; 82 Node* root = create(0,n-1,0,n-1);//先序+中序重建二叉树 83 preorder(root);//先序遍历 84 printf("\n"); 85 num = 0; 86 inorder(root);//中序遍历 87 printf("\n"); 88 num = 0; 89 postorder(root);//后序遍历 90 printf("\n"); 91 num = 0; 92 BFS(root); //层次遍历 93 return 0; 94 }


浙公网安备 33010602011771号