重建二叉树
2013-03-18 08:44
239 查看
何海涛:《剑指Offer:名企面试官精讲典型编程题》:九度OJ
题目描述:http://ac.jobdu.com/problem.php?cid=1039&pid=1
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。
输入:
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为一个整数n(1<=n<=1000):代表二叉树的节点个数。
输入的第二行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的前序遍历序列。
输入的第三行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的中序遍历序列。
输出:
对应每个测试案例,输出一行:
如果题目中所给的前序和中序遍历序列能构成一棵二叉树,则输出n个整数,代表二叉树的后序遍历序列,每个元素后面都有空格。
如果题目中所给的前序和中序遍历序列不能构成一棵二叉树,则输出”No”。
样例输入:
样例输出:
代码AC:
思想:使用分治左右建树即可!
题目描述:http://ac.jobdu.com/problem.php?cid=1039&pid=1
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。
输入:
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为一个整数n(1<=n<=1000):代表二叉树的节点个数。
输入的第二行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的前序遍历序列。
输入的第三行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的中序遍历序列。
输出:
对应每个测试案例,输出一行:
如果题目中所给的前序和中序遍历序列能构成一棵二叉树,则输出n个整数,代表二叉树的后序遍历序列,每个元素后面都有空格。
如果题目中所给的前序和中序遍历序列不能构成一棵二叉树,则输出”No”。
样例输入:
8
1 2 4 7 3 5 6 8
4 7 2 1 5 3 8 6
8
1 2 4 7 3 5 6 8
4 1 2 7 5 3 8 6
样例输出:
7 4 2 5 8 6 3 1
No
代码AC:
思想:使用分治左右建树即可!
#include <stdio.h> #include <stdlib.h> typedef struct tree { int id; struct tree * lc; struct tree * rc; }tree, *p_tree; p_tree root; int *pre, *mid; int creat_tree( int low, int high, p_tree *t, int m_low, int m_high ) { int i, count = 0, f1, f2; int flag; if( high - low != m_high - m_low ) { return 0; } if( low > high ) // 细节 { return 1; } (*t) = ( p_tree )malloc( sizeof( tree ) ); (*t)->id = pre[low]; (*t)->lc = NULL; (*t)->rc = NULL; // if( low == high ) // 细节 // { // return 1; // } flag = 0; for( i = m_low; i <= m_high; i++ ) { if( mid[i] == pre[low] ) { flag = 1; break; } else { count++; } } if( flag ) { f1 = creat_tree( low + 1, low + count, &((*t)->lc), m_low, m_low + count - 1 ); if( !f1 ) { return 0; } f2 = creat_tree( low + count + 1, high, &((*t)->rc), m_low + count + 1, m_high ); return f2; } else { return 0; } } void out_put( p_tree t ) { if( t ) { out_put( t->lc ); out_put( t->rc ); printf("%d ", t->id); } } int main() { int i, n; while( scanf("%d", &n) != EOF ) { pre = ( int* )malloc( sizeof( int ) * n ); mid = ( int* )malloc( sizeof( int ) * n ); for( i = 0; i < n; i++ ) { scanf("%d", &pre[i]); } for( i = 0; i < n; i++ ) { scanf("%d", &mid[i]); } if( creat_tree( 0, n - 1, &root, 0, n - 1 ) ) { out_put( root ); } else { printf("No"); } printf("\n"); } return 0; }
相关文章推荐
- 剑指offer-重建二叉树
- 重建二叉树
- 由中根序列和后根序列重建二叉树
- 根据二叉树的先序、中序遍历结果重建二叉树
- 重建二叉树
- 剑指offer 6- 重建二叉树
- 华为OJ 重建二叉树
- 前中序重建二叉树python实现
- 面试题五 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 【剑指offer-Java版】06重建二叉树
- 重建二叉树(根据前序和中序遍历结果)
- 由前序遍历和中序遍历重建二叉树
- Python利用前序和中序遍历结果重建二叉树的方法
- [牛客网,剑指offer,python] 重建二叉树
- 二叉树重建
- 【006】重建二叉树
- 通过前序遍历和中序遍历重建二叉树以及输出后序遍历(Java实现)(二)