根据先序/中序或后序/中序构建二叉树基本算法分析
2014-02-26 21:55
519 查看
今天做PAT的时候,发现有几道题是关于先序/中序或后序/中序构建二叉树的,特此处总结分析,以便后序复习:
我这边以根据后序和中序来得出层次遍历的序列为例分析:
基本思想:
1、根据后序序列最后一个元素找到根节点
2、根据这个根节点在中序序列中找到该根节点,刚好把序列分成左子树和右子树
3、递归调用,即可构建二叉树
然后再根据需要输出先序遍历、后序遍历、中序遍历或者层次遍历
具体例子的理解可以参考代码上面的注释
练习题可参考浙大PAT的1020. Tree Traversals (25)
AC的参考代码:
我这边以根据后序和中序来得出层次遍历的序列为例分析:
基本思想:
1、根据后序序列最后一个元素找到根节点
2、根据这个根节点在中序序列中找到该根节点,刚好把序列分成左子树和右子树
3、递归调用,即可构建二叉树
然后再根据需要输出先序遍历、后序遍历、中序遍历或者层次遍历
具体例子的理解可以参考代码上面的注释
练习题可参考浙大PAT的1020. Tree Traversals (25)
AC的参考代码:
#include <iostream> #include <queue> using namespace std; struct Node { //定义二叉树节点 int value; Node *leftLeaf; Node *rightLeaf; }; int N; int isTree = 1; //用来判断能否构成二叉树 Node *builtTree(int *post,int *in,int length){ //根据中序和后序序列建立二叉树 Node *root = new Node(); root->value = post[length-1]; root->leftLeaf = NULL; root->rightLeaf = NULL; int index; for(index=0;index<length;index++){ //找根节点的位置 if(in[index]==root->value) break; } if(index>=length){ //没在合适的范围内找到根节点,无法构建树 isTree = 0; return NULL; } if(index>0){ //存在左子树 root->leftLeaf = builtTree(post,in,index); //参数:post起始点,in起始点,数组长度 } if(length-index-1>0){ //存在右子树 root->rightLeaf = builtTree(post+index,in+index+1,length-index-1); } return root; } void printLevel(Node *root){ //输出层次遍历序列 int countTotal = 1; queue<Node> qu; //层次遍历用队列实现 qu.push((*root)); while(!qu.empty()){ Node temp = qu.front(); qu.pop(); countTotal<N?cout<<temp.value<<" ":cout<<temp.value; //去掉最后的那个空格 countTotal++; if(temp.leftLeaf!=NULL){ qu.push(*temp.leftLeaf); } if(temp.rightLeaf!=NULL){ qu.push(*temp.rightLeaf); } } } int main() { cin>>N; int post ; int in ; for(int i=0;i<N;i++){ cin>>post[i]; } for(int i=0;i<N;i++){ cin>>in[i]; } Node *root = builtTree(post,in,N); printLevel(root); return 0; }
相关文章推荐
- 根据前序、中序构建二叉树
- (树)根据中序后序构建二叉树
- 某国内IT大牌名企校招笔试 + 树的学习—(递归构建二叉树、递归非递归前序中序后序遍历二叉树、根据前序序列、中序序列构建二叉树)
- 算法竞赛入门经典:第六章 数据结构基础 6.9 根据二叉树的后序和中序确定前序序列
- 根据前序和中序,构建二叉树
- 剑指offer04--根据前序和中序构建二叉树
- [Java算法分析与设计]中序线索化二叉树
- 二叉树(二) 求二叉树高度,根据先序和中序构建二叉树,判断二叉树是否是完全二叉树,判断两棵树是否相等
- 根据前序和中序构建二叉树
- Offer题6 根据前序和中序构建二叉树
- 二叉树系列——根据前序和中序、中序和后序构建二叉树
- 【数据结构与算法】根据遍历结果构建二叉树
- 给定先序:ABCDEFGHIJK 给定中序:CBEDGFAHJIK 首先分析上述给定的先,中序,首先得知先序遍历的肯定是二叉树的根节点:A,在看中序遍历,根据中序遍历的原理可知,在A左边的一定全部属于
- 根据二叉树的前序和中序构建二叉树
- 树的学习——(递归构建二叉树、递归非递归前序中序后序遍历二叉树、根据前序序列、中序序列构建二叉树)
- 算法--根据二叉树前序和中序遍历序列,求后续遍历序列
- 根据前序遍历和中序遍历构建二叉树以及根据中序遍历后序遍历构建二叉树
- 根据中序和先序(后序)构建二叉树
- 根据中序和前序遍历构建二叉树
- LeetCode: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium