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 }
  • 相关阅读:
    Windows下载Vim
    分享:分享几个程序员使用的网站
    分享:C语言大礼包(PDF)
    将vscode打造成强大的C/C++ IDE
    最适合做C/C++开发的IDE
    bzoj 2244
    bzoj 1492
    bzoj 3262
    bzoj 1176
    bzoj 2961
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4558682.html
Copyright © 2011-2022 走看看