重建二叉树
来源:互联网 发布:中铁建沙特知乎 编辑:程序博客网 时间:2024/05/22 09:01
1.问题描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出改二叉树。假设输入的前序遍历序列和中序遍历序列的结果中都不包含重复的数字。例如输入前序遍历的序列{1,2,4,7,3,5,6,8}和中序遍历的序列{4,7,2,1,5,3,,8,6},则重建出二叉树,并输出它的头结点。(来自《剑指offer》)
2.分析
由于我们知道二叉树的先序和中序序列。先序 1,2,4,7,3,5,6,8。中序4,7,2,1,5,3,8,6 。那么先序中的第一个结点 1 为树的根,接下来找到 1 在中序序列中的位置,在 1 前面的序列为左子树,在1后面的序列为右子树,然后在左右子树中在继续重复这个过程,直到树被重建成功。
3.代码
#include <stdio.h>#include <stdlib.h>typedef int data;typedef struct Node{ struct Node* lChild; struct Node* rChild; data data;}Tree;// 查找key在数组中的位置。从1开始计数,如果为0说明未查找到。int GetLocationInArray(int* array, data key, int length){ if (array == NULL || length <= 0) { return 0; } int index = 1; while (index <= length) { if (key == array[index - 1]) { return index; } index ++; } return 0;}//length代表树或子树在先序或中序序列数组中占的长度Tree* RebuildTree(int* preOrder, int* inOrder,int length){ if (preOrder == NULL || inOrder == NULL || length <= 0) { return NULL; } Tree *root = (Tree*)malloc(sizeof(Tree)); root->data = *(preOrder); int location = GetLocationInArray(inOrder, root->data, length); if(location == 0) { return NULL; } root->lChild = RebuildTree(preOrder + 1, inOrder, location-1); root->rChild = RebuildTree(preOrder + location, inOrder + location, length-location); return root;}
二叉树中 有一个堆和红黑树。堆分为最大堆和最小堆,最大堆中根结点的值最大,最小堆中根结点的值最小。很多需要快速找到最大值和最小值的问题都可以用堆来解决。
红黑树 是把 树中的结点定义为红,黑俩种颜色,并通过规则确保从根结点到叶结点的最长路径长度不超过最短路径长度的两倍。在c++的stl中,set multiset map multimap等都是基于红黑树实现的。
0 0
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 碎语
- hibernate一对一主键双向关联
- php-fpm错误
- Q.2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only acce
- python进行文档抽取与解析的简单实现
- 重建二叉树
- tomcat密码管理
- OpenCV基础07(序列)
- centos添加用户
- 2004
- 当析构函数遇到多线程 ── C++ 中线程安全的对象回调
- 使用 Python 开始游戏开发
- centos nginx设置多站点
- Q2.4 Partition List