先序中序重建二叉树
来源:互联网 发布:win10 app设计软件 编辑:程序博客网 时间:2024/05/29 09:32
基本思路:
1、先序遍历第一个结点作为根节点。
2、在中序遍历中查找根节点的位置,以此为界将中序遍历序列划分为左右两个序列(左、右子树)。
3、根据左、右子树在中序序列中的结点个数,将先序序列去掉根结点后的序列划分为左、右两个序列,它们分别为左、右子树的先序序列。
4、对左、右子树的先序序列和中序序列递归实施同样方法,直到左、右子树为空。
#include <stdio.h>#include <stdlib.h>typedef struct TNode{ int data; struct TNode *lchild,*rchild; } TNode,*PTNode;//先序遍历输出二叉树void print(PTNode root){ PTNode ptnode = root; if(ptnode!=NULL) { printf("%d ",ptnode->data); print(ptnode->lchild); print(ptnode->rchild); } } //利用先序中序遍历重构二叉树PTNode rebuild(int *startPreorder,int *endPreorder,int *startInorder,int *endInorder){ int rootvalue = startPreorder[0]; PTNode root = (PTNode)malloc(sizeof(TNode)); root->data = rootvalue; root->lchild = root->rchild = NULL; if(startPreorder == endPreorder) { if(startInorder == endInorder && *startPreorder == *startInorder) { return root; } else { printf("input error!\n"); exit(-1); } } //在中序遍历中找根节点的值 int *rootInorder = startInorder; while(rootInorder<=endInorder && *rootInorder != rootvalue) ++rootInorder; if(rootInorder == endInorder && *rootInorder != rootvalue) { printf("input error!\n"); exit(-1); } int leftLength = rootInorder-startInorder; int *leftPreorderEnd = startPreorder+leftLength; //构建左子树 if(leftLength>0) { root->lchild = rebuild(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1); } //构建右子树 if(leftLength<endPreorder-startPreorder) { root->rchild = rebuild(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder); } return root;}PTNode rebuildTree(int *preorder,int *inorder,int length){ if(preorder == NULL || inorder == NULL || length<=0) return NULL; return rebuild(preorder,preorder+length-1,inorder,inorder+length-1);}int main(int argc, char *argv[]) { int pre[] = {1,2,3}; int in[] = {2,1,3}; PTNode root = rebuildTree(pre,in,sizeof(pre)/sizeof(pre[0])); print(root); return 0;}
0 0
- 先序中序重建二叉树
- 编程之美-先序中序 重建二叉树
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 重建二叉树
- 关于Visual Studio几个基本的概念
- 利用反射获取子类,父类,接口的信息
- Office 2016 每次打开都有配置进度 解决办法
- 不同数据库之间的基本函数
- 计算机网络(七)--TCP的可靠传输原理及实现(二)
- 先序中序重建二叉树
- 文件夹查找操作 CFileFind类的IsDots()和IsDictionary()函数
- Android Service与Activity之间通信的几种方式
- LeetCode 338. Counting Bits
- css3效果大杂烩
- DynamicCocoa:滴滴 iOS 动态化方案的诞生与起航
- TCP/IP-IP
- C# AspriseOCR 验证码识别(第一讲)
- 非广州户籍在校研究生办理港澳通行证和护照心得