zoukankan      html  css  js  c++  java
  • [hihoCoder] 后序遍历

    The key of this problem is that we need not build the tree from scratch. In fact, we can direct obtain its post-order traversal results in a recursive manner and the problem has given nice hints on this.

    The code is as follows.

     1 #include <iostream>
     2 #include <string>
     3 
     4 using namespace std;
     5 
     6 string post_order(string pre_order, string in_order) {
     7     if (pre_order.empty() && in_order.empty())
     8         return "";
     9     if (pre_order.length() == 1 && in_order.length() == 1)
    10         return pre_order;
    11     string root = pre_order.substr(0, 1);
    12     int rootInOrder = 0;
    13     while (in_order[rootInOrder] != pre_order[0])
    14         rootInOrder++;
    15     string pl = pre_order.substr(1, rootInOrder);
    16     string pr = pre_order.substr(1 + pl.length(), pre_order.length() - pl.length() - 1);
    17     string il = in_order.substr(0, rootInOrder);
    18     string ir = in_order.substr(rootInOrder + 1, in_order.length() - il.length() - 1);
    19     return post_order(pl, il) + post_order(pr, ir) + root;
    20 }
    21 
    22 int main(void) {
    23     string pre_order, in_order;
    24     while (cin >> pre_order >> in_order)
    25         cout << post_order(pre_order, in_order);
    26     return 0;
    27 }
  • 相关阅读:
    Zookeeper and The Infinite Zoo(CF1491D)(位运算)
    树上差分
    最近公共祖先
    极角排序
    最长路spfa
    树的基础
    树的遍历~
    最小圆覆盖板子
    动态凸包(询问点是否在凸包内部)
    凸包内最大三角形
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4558682.html
Copyright © 2011-2022 走看看