[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 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值