zoukankan      html  css  js  c++  java
  • POJ 2255(分治递归)

             已知树的先序和中序,求后序。

             虽然涉及树,感觉递归思想及其强烈,就分到递归类了。

             本人递归思想较差,做了好久都不会,经同学指点才得以AC。

            核心:先序的第一个r肯定是树的根,中序以r分隔,左边是左子树,右边是右子树。

    二叉树 就是这样给建立的。每个子树也可以来整。所以就递归了,把树给构造出来,再后序遍历之。

    代码:

     1 #include<iostream>
    2 #include<map>
    3 #include<string>
    4 using namespace std;
    5
    6 struct node
    7 {
    8 char ch;
    9 struct node *left,*right;
    10 };
    11
    12 map<char , int> pre;
    13 struct node * create(string cmid);
    14 void postorder(struct node *tree);
    15
    16 int main()
    17 {
    18 struct node *head;
    19 string a,b;
    20 int i,len;
    21
    22 while(cin>>a>>b)
    23 {
    24 len = a.length();
    25 for(i = 0 ; i < len ; ++i)
    26 pre[a[i]] = i;//将先序遍历中的字符和位置建立映射
    27
    28 head = create(b);
    29 postorder(head);
    30 cout<<endl;
    31 }
    32 //system("pause");
    33 return 0;
    34 }
    35
    36 struct node * create(string cmid)
    37 {
    38 int i,index;
    39 struct node *root;
    40 root = new node;
    41
    42 if(cmid == "") return root = NULL;//如果string为空了,就说名到叶子了
    43 index = 0;
    44 for( i = 0; i < cmid.length(); ++i)
    45 if(pre[cmid[index]] > pre[cmid[i]])//寻找根在中序遍历序列的位置
    46 index = i;
    47
    48 root->ch = cmid[index];//感觉就是一个不断找根的过程
    49 root->left = create(cmid.substr(0,index));
    50 root->right = create(cmid.substr(index+1));
    51
    52 return root;
    53 }
    54 void postorder(struct node *tree)
    55 {
    56 if(tree == NULL) return ;
    57 postorder(tree->left);
    58 postorder(tree->right);
    59 cout<<tree->ch;
    60 }



  • 相关阅读:
    精确覆盖DLX算法模板另一种写法
    Hdu3498-whosyourdaddy(精确覆盖模板题)
    精确覆盖DLX算法模板
    Object2Map
    Use ResourceBundle read properties file.
    Kendo UI Example(grid)
    Kendo 日期控件
    Spring mvc 中文乱码问题解决方法
    Thread communication java.util.concurrent.locks.Condition 用法(二)
    Thread communication java.util.concurrent.locks.Condition 用法(一)
  • 原文地址:https://www.cnblogs.com/HpuAcmer/p/2429994.html
Copyright © 2011-2022 走看看