[2016-01-21][HDU][1710]

[2016-01-21][HDU][1710]

  • /*************************************************************
  • 时间:2016-01-20  16:47:06  星期三
  • 题目编号:J
  • 题目大意:已知二叉树 前序遍历和中序遍历的结果,求后序遍历的结果
  • 方法:直接对树的子树进行dfs,直到子树为叶子
  • 解题过程遇到问题:
    • 第一个 dfs,忘记吧参数改成n ,写成 dfs(0,8,0,8)
    • 把结果整合成字符串输出 WA,结果一个一个整数输出才对!
    • 如果保证dfs成功,那么可以在返回前 do something,比如保存路径之类,而不需要 通过dfs的返回值进行相关判断
  • *************************************************************/  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int T[2][1010],n;//T[0]保存前序遍历的结果  T[1]保存中序遍历的结果
 
//L_0 R_0表示当前树,前序遍历对应结果的范围  L_1 R_1表说中序遍历结果的范围
void dfs(int L_0,int R_0,int L_1,int R_1)
{
    int flg = 0;
    int root = T[0][L_0];
 
    //查找当前树的树根 在中序遍历结果中的位置  ,其中  T[0][L_0] 表示 树根的值
    //int pos_root_1 = find( T[1] + L_1 , T[1] + R_1 + 1,root ) - T[1];
    int pos_root_1 = 0;
    while(1){
        if(T[1][pos_root_1] == T[0][L_0])
            break;
        pos_root_1++;
    }
 
    //确定 两个子树的范围,并进行dfs
    int lenleft = pos_root_1 - L_1;
    if(L_0 + 1 <= R_0 && L_0 + lenleft <= R_0 && L_0 + 1 <= L_0 + lenleft && pos_root_1-1 >= L_1)
        dfs(L_0 + 1,L_0 + lenleft,L_1,pos_root_1-1 );
 
    if(L_0 + lenleft + 1 <= R_0 &&pos_root_1 + 1<=R_1 )
        dfs(L_0 + lenleft + 1,R_0,pos_root_1 + 1,R_1);
 
    //输出结果,
    printf("%d",T[0][L_0]);
    if(T[0][L_0]==T[0][0]) printf("\n");
    else printf(" ");
}
int main(){
    while(~scanf("%d",&n)){
 
        for(int i = 0;i < 2;i++)
            for(int j = 0;j < n;j++)
                scanf("%d",&T[i][j]);
 
        dfs(0,n-1,0,n-1);
    }
    return 0;
}




来自为知笔记(Wiz)


posted on 2016-01-21 21:58  红洋  阅读(97)  评论(0)    收藏  举报

导航