2. 重建二叉树
来源:互联网 发布:国外电视台直播软件apk 编辑:程序博客网 时间:2024/05/06 16:27
例子:
我们先来看一个例子,二叉树如上图,则先序遍历为:1 2 4 7 3 5 6 8,中序遍历为:4 7 2 1 5 3 8 6
思路:
先序遍历中的第一个元素为根节点,这个元素将中序遍历划分为左右两个部分,左边的为左子树的中序遍历,右边的为右子树的中序遍历,同样也可以将先序遍历除了第一个元素以外的划分为两个部分,第一个部分是左子树的先序遍历,第二部分是右子树的先序遍历。
由此可知,这是一个递归过程,可以利用递归函数来构建二叉树。对于二叉树的这种常见操作要熟悉,实现的代码要会写。
代码:
#include <stdio.h>#include <stdlib.h>// the binary tree nodetypedef struct BTNode{int key;struct BTNode *lchild;struct BTNode *rchild;}BTNode;// find the key in the InOrder array, if not finded then return -1int findKey(int arr[], int start, int end, int key) {int i;for (i = start; i <= end; i++)if (arr[i] == key)return i;return -1;}// create the binary tree by PreOrder and InOrderBTNode *rebuildTree(int pre[], int startPre, int endPre, int in[], int startIn, int endIn) {// both order have the same sizeif (endPre - startPre != endIn - startIn)return NULL;// the root is the first node of PreOrderBTNode *root = (BTNode *) malloc(sizeof(BTNode));root->key = pre[startPre];root->lchild = NULL;root->rchild = NULL;// find the index of root node in the InOrderint mid = findKey(in, startIn, endIn, pre[startPre]);if (mid == -1)return NULL;// if the left-subtree exists, create left-subtreeint length;if (mid > startIn) {length = mid - startIn;root->lchild = rebuildTree(pre, startPre + 1, startPre + 1 + length - 1, in, startIn, startIn + length - 1);}// if the right-subtree exists, create right-subtreeif (mid < endIn) {length = endIn - mid;root->rchild = rebuildTree(pre, endPre - length + 1, endPre, in, endIn - length + 1, endIn);}return root;}void postTraverse(BTNode *tree) {if (tree) {postOrder(tree->lchild);postOrder(tree->rchild);printf("%d ", tree->key);}}int main() { int preOrder[8] = {1, 2, 4, 7, 3, 5, 6, 8}; int inOrder[8] = {4, 7, 2, 1, 5, 3, 8, 6}; BTNode *root = rebuildTree(preOrder, 0, 7, inOrder, 0, 7); postTraverse(root); printf("\n"); return 0;}
0 0
- 2. 重建二叉树
- 2. 重建二叉树
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 重建二叉树
- python 打日志学习
- 如何在指定目录下获取指定文件尾缀的文件名
- HTTP协议详解
- Android Adapter推荐写法
- 科学的美
- 2. 重建二叉树
- 刚学jquery,记下知识点
- 杨辉三角7.24
- json“不能用”方括号访问
- Android修改软键盘回车键并监听
- UVA12186
- Linux /bin, /sbin, /usr/bin, /usr/sbin 区别 http://blog.csdn.net/xh16319/article/details/12861523
- 【BZOJ 2286】消耗战(虚树)
- 【黑马程序员】----java基础----网络编程