7-23 还原二叉树 (25分)

参考博客链接

 

递归思想:

先序遍中的X节点,当它出现在中序遍历中时,以中序遍历中X为分界点,它的左边部分为X的左子树,右边部分为X的右子树,然后依次规则递归处理它的左右子树。

核心代码:

用两个数组分别存储前序、中序遍历结果。s1为前序遍历数组中要处理的树的下标起点,e1为终点。同理s2为中序遍历数组中待处理的树的起点,e2为终点。

 

 

 1 Tptr build(int s1, int e1, int s2, int e2) 
 2 {
 3     Tptr Head = Create();
 4     Head->data = r1[s1];
 5     for(int i = s2; i<=e2; i++)
 6     {  
 7         if(i!=s2)Head->left = build(s1+1, s1+i-s2, s2, i-1);//通过计算左右子树长度可以推出待处理树的下标范围,然后作为形参传入
 8         if(i!=e2)Head->right = build(s1+i-s2+1,e1,i+1,e2);
 9         break;
10     }
11     return Head;
12 }

 

完整AC代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 typedef struct BTNode* Tptr;
 7 char r1[100], r2[100];
 8 
 9 struct BTNode
10 {
11     char data;
12     Tptr left, right;
13 };
14 Tptr Create()
15 {
16     Tptr T = new struct BTNode;
17     T->left = T->right = NULL;
18     return T;
19 }
20 Tptr build(int s1, int e1, int s2, int e2)
21 {
22     Tptr Head = Create();
23     Head->data = r1[s1];
24     for (int i = s2; i <= e2; i++)
25     {
26         if (r2[i] == r1[s1])
27         {
28             if (i != s2)Head->left = build(s1 + 1, s1 + i - s2, s2, i - 1);
29             if (i != e2)Head->right = build(s1 + i - s2 + 1, e1, i + 1, e2);     
30             break;
31         }
32     }
33     return Head;
34 }
35 int GetH(Tptr T)
36 {
37     if (!T)return 0;
38     if (!T->left)GetH(T->left);
39     if (!T->right)GetH(T->right);
40     return GetH(T->left) > GetH(T->right) ? GetH(T->left) + 1 : GetH(T->right) + 1;
41 }
42 int main()
43 {
44     int n;
45     cin >> n;
46     cin >> r1;
47     cin >> r2;
48     Tptr T = build(0, n - 1, 0, n - 1);
49     cout << GetH(T);
50     return 0;
51 }

 

posted @ 2020-03-07 17:14  幻想Elapse  阅读(403)  评论(0编辑  收藏  举报