二叉树遍历
来源:互联网 发布:unity3d安装步骤 编辑:程序博客网 时间:2024/06/06 05:54
二叉树遍历习题
题意:
给出一个二叉树的后序遍历序列和中序遍历序列,求这颗二叉树的层序遍历序列。
输入
72 3 1 5 7 6 41 2 3 4 5 6 7
输出
4 1 6 3 5 7 2
#include <iostream>#include <cstring>#include <queue>#include <algorithm>using namespace std;const int maxn=50;typedef struct node{ int data; node* lchild; node* rchild;}Node;int pre[maxn],in[maxn],post[maxn]; //先序,中序,后序 int n; //结点个数 //create 函数返回构建出的二叉树的根结点地址Node* create( int postL,int postR,int inL,int inR ) { if(postL > postR) { return NULL; //后序序列长度小于等于0时,直接返回 } Node* root = new Node; root->data = post[postR]; //新结点的数据域为根结点的值 int k; for(k=inL;k<=inR;k++) { if(in[k] == post[postR] ) //根据先序序列中根结点的值,在中序序列中找出根结点的位置 { break; } } int num_left=k-inL; //左子树的结点个数 //分治递归创建左子树和右子树 root->lchild = create(postL,postL+num_left-1,inL,k-1); root->rchild = create(postL+num_left,postR-1,k+1,inR); return root; }//已经输出的结点的个数 int num=0;void BFS(Node* root){ queue<Node*> queue; queue.push(root); while(!queue.empty()) { Node* now=queue.front(); queue.pop(); printf("%d",now->data); num++; if(num<n) { printf(" "); } if(now->lchild!=NULL) { queue.push(now->lchild); } if(now->rchild!=NULL) { queue.push(now->rchild); } }}int main(){ scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&post[i]); } for(int i=0;i<n;i++) { scanf("%d",&in[i]); } Node* root= create(0,n-1,0,n-1); BFS(root); return 0;}
阅读全文
0 0
- 二叉树遍历、分层遍历
- 遍历二叉树--二叉树
- 【树】遍历二叉树
- 二叉树遍历
- 二叉树遍历
- 二叉树的遍历
- (原创)遍历二叉树
- 二叉树遍历-php
- 查找--遍历二叉树
- 遍历二叉树
- 二叉树遍历规则
- 二叉树的遍历
- 二叉树遍历
- 遍历二叉树
- 二叉树遍历问题
- 二叉树遍历
- 二叉树遍历(zz)
- 二叉树的遍历
- Win10安装 JDK 及配置环境变量的方法
- 为什么需要静态方法?
- NOIP普及组题解(能有民间数据的三题)
- java内存泄露分析方案
- 数据集总结(未完)
- 二叉树遍历
- Flipping Burned Pancakes --模拟
- 动态栈的创建
- 非Python的Web服务器之Apache WSGI模块安装
- Maven异常:Could not find artifact
- linux 中用vi编辑器替换字符
- 多重检验中的FDR错误控制方法与p-value的校正及Bonferroni校正
- 一个工厂的网络实践,原本简单的网络被搞得如此复杂
- Leetcode 5. Longest Palindromic Substring (第十周作业)