HDU
来源:互联网 发布:qq农场运输机数据 编辑:程序博客网 时间:2024/06/03 19:09
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
91 2 4 7 3 5 8 9 64 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1
题意:给你前序,中序遍历,让你输出后序遍历;
题解:和构建二叉树差不多,代码里,有解释;
代码:
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define Max 1010int f;void build(int n,int *s1,int *s2){if(n<=0) return ; int i,p;for(i=0;i<n;i++) // 找出以s1[0]为根节点的左子树; {if(s2[i]==s1[0])break; }p = i;build(p,s1+1,s2); //构建左子树;p是以s1[0] 为根节点的左子树的结点个数;build(n-p-1,s1+p+1,s2+p+1); //构建右子树,n-p-1就是以s1[0]为根节点的右子树的结点个数; //s2[0] 永远就是以s1[0]为根节点的树的中序遍历的第一个节点; if(!f){printf("%d",s1[0]);f=1;}else printf(" %d",s1[0]);}int main(){int i,j,n;int s1[Max],s2[Max];while(~scanf("%d",&n)){for(i=0;i<n;i++)scanf("%d",&s1[i]);for(i=0;i<n;i++)scanf("%d",&s2[i]);f=0;build(n,s1,s2);printf("\n");}return 0;}
阅读全文
0 0
- hdu
- hdu
- HDU
- hdu ()
- hdu
- hdu
- HDU
- HDU
- hdu
- hdu
- HDU
- Hdu
- hdu
- hdu-
- hdu
- hdu
- hdu
- HDU
- 学习笔记:服务器shell编辑命令
- Python 4)面向对象的进一步拓展
- 11进程与线程
- UOJ 148/bzoj 1650(二分)(NOIP 2015)
- 010day(学习用freopen重定向输入和循环例题的练习)
- HDU
- 一道例题
- 黑客基础知识<百度文库>
- ImageLoader原理分析
- 洛谷 P2574 XOR的艺术
- 登陆验证码的实现
- 657. Judge Route Circle
- 投掷模板
- IllegalArgumentException in class: domain.User, setter method of property: birthda