码迷,mamicode.com
首页 > 其他好文 > 详细

1020 Tree Traversals (25 分)

时间:2019-11-25 18:02:45      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:iostream   src   output   main   ber   sam   code   secure   ios   

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2
分析:根据后序遍历和中序遍历 输出层序遍历
我的做法是利用后序遍历和中序遍历建树 再层序遍历输出
利用两个变量来记录我们需要建子树的范围 另一个变量记录每层的根节点
技术图片
 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include<iostream>
 3 #include<vector>
 4 #include<queue>
 5 #include<stack>
 6 #include<algorithm>
 7 using namespace std;
 8 typedef struct BtNode* Bt;
 9 struct BtNode
10 {
11     int Num;
12     Bt RT;
13     Bt LT;
14 };
15 vector<vector<int> > Order(2);
16 Bt BuildTree(Bt T,int i2,int j2,int j1)
17 {
18     if (i2 >= j2)
19         return T;
20     int i = i2;
21     for (; i < j2; i++)
22     {
23         if (Order[1][i] == Order[0][j1 - 1])
24             break;
25     }
26     if (!T)
27     {
28         T = new BtNode();
29         T->LT = NULL;
30         T->RT = NULL;
31         T->Num = Order[1][i];
32     }
33     T->LT =BuildTree(T->LT,i2,i,j1-j2+i);
34     T->RT = BuildTree(T->RT,i+1,j2,j1-1);
35     return T;
36 }
37 int main()
38 {
39     int N;
40     cin >> N;
41     int num;
42     for(int i=0;i<2;i++)
43         for (int j = 0; j < N; j++)
44         {
45             cin >> num;
46             Order[i].push_back(num);
47         }
48     Bt T=NULL;
49     T = BuildTree(T,0,N,N);
50     queue<Bt> Q;
51     Q.push(T);
52     cout << T->Num;
53     while (!Q.empty())
54     {
55         if (Q.front()->LT)
56         {
57             Q.push(Q.front()->LT);
58             cout << " " << Q.front()->LT->Num;
59         }
60         if (Q.front()->RT)
61         {
62             Q.push(Q.front()->RT);
63             cout << " " << Q.front()->RT->Num;
64         }
65         Q.pop();
66     }
67     return 0;
68 }
View Code

 

1020 Tree Traversals (25 分)

标签:iostream   src   output   main   ber   sam   code   secure   ios   

原文地址:https://www.cnblogs.com/57one/p/11929098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!