根据前序遍历序列和中序遍历序列构造二叉树算法
来源:互联网 发布:矩阵和伴随矩阵的秩 编辑:程序博客网 时间:2024/05/17 23:39
http://blog.csdn.net/yunzhongguwu005/article/details/9270085
1 确定根,确定左子树,确定右子树
2 在左子树中递归
3 在右子树中递归
4 打印当前根
I 前序遍历的第一个就是根。
II 中序遍历根据根,分成左子树和右子树。
III 重复I步
1 确定根,确定左子树,确定右子树
2 在左子树中递归
3 在右子树中递归
4 打印当前根
I 前序遍历的第一个就是根。
II 中序遍历根据根,分成左子树和右子树。
III 重复I步
#include <iostream>#include <string>#include "stdlib.h"using namespace std;typedef struct BiNode{ char data; struct BiNode *lchild; struct BiNode *rchild;}BiNode,*BiTree;void CreateBiTree(BiTree&t, string presequence,string insequence){ //it is leaf if (presequence.length()==0) { t=NULL; return ; } //root char rootNode=presequence[0]; //root location in inorder int index=insequence.find(rootNode); //left child sequence string lchild_insequence=insequence.substr(0,index); //right chlid sequence string rchild_insequence=insequence.substr(index+1); //left child length int lchild_length=lchild_insequence.length(); //right child length int rchild_length=rchild_insequence.length(); //left child presequence string lchild_presequence=presequence.substr(1,lchild_length); //right child presequence string rchild_presequence=presequence.substr(1+lchild_length); t=(BiTree)malloc(sizeof(BiNode)); if (t!=NULL) { t->data=rootNode; CreateBiTree(t->lchild,lchild_presequence,lchild_insequence); CreateBiTree(t->rchild,rchild_presequence,rchild_insequence); }}void PreOrderTraverse(BiTree&t){ if (t!=NULL) { cout<<t->data; PreOrderTraverse(t->lchild); PreOrderTraverse(t->rchild); }}void InOrderTraverse(BiTree&t){ if (t!=NULL) { InOrderTraverse(t->lchild); cout<<t->data; InOrderTraverse(t->rchild); }}main(){ BiTree t; string presequence="ABCDEFG"; string insequence="CBEDAFG";; CreateBiTree(t,presequence,insequence); PreOrderTraverse(t); cout<<endl; InOrderTraverse(t); getchar(); return 0;}
0 0
- 根据前序遍历序列和中序遍历序列构造二叉树算法
- 根据前序遍历序列和中序遍历序列构造二叉树算法
- 根据前序遍历序列和中序遍历序列构造二叉树算法
- 根据前序遍历序列和中序遍历序列构造二叉树
- 根据前序遍历序列和中序遍历序列构造二叉树
- 前序遍历序列和中序遍历序列构造二叉树算法
- C++ 根据前序遍历序列和中序遍历序列可以构造唯一的二叉树
- 根据中序和层次遍历序列,构造二叉树
- 算法面试:根据前序遍历结果序列和中序遍历结果序列重构二叉树
- 如何根据前序遍历序列和中序遍历序列确定二叉树
- 根据前序遍历序列和中序遍历序列重建二叉树
- 根据前序遍历序列和中序遍历序列重建二叉树
- 根据前序遍历序列和中序遍历序列创建二叉树
- 如何根据前序遍历序列和中序遍历序列确定二叉树
- 由二叉树的前序遍历序列和中序遍历序列求后序遍历序列
- 剑指Offer_06 根据前序遍历和中序遍历序列 重建二叉树
- 根据二叉树的前序遍历序列和中序遍历序列求二叉树的后序遍历序列
- 根据前序遍历(或者是后序遍历)和中序遍历得到的序列可以重建二叉树
- PhpStorm无法使用Terminal解决方法
- Maven那点事儿(Eclipse版)
- ue4 中动画控制,利用conduit节点
- JAVA学习笔记----接口、抽象类、内部类
- 【CDP-云设计模式】第6章,3.直接对象上传模式(Direct Object Upload Pattern)
- 根据前序遍历序列和中序遍历序列构造二叉树算法
- 数据结构实验:连通分量个数
- oracle数据恢复
- C#人民币金额大写
- HDU 2066 一个人的旅行
- SQL 教程简介
- 【HDU】-2112-HDU Today(最短路)
- 最新基于高德地图的android进阶开发(6)感兴趣点(POI)周边搜索源码浅析
- Android Sipdroid 语音通话项目简单使用