[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...

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 }
目录
相关文章
|
9月前
|
Linux
数据结构实验之求二叉树后序遍历和层次遍历
数据结构实验之求二叉树后序遍历和层次遍历
|
9月前
二叉树的前序遍历、中序遍历、后序遍历
二叉树的前序遍历、中序遍历、后序遍历
1339:【例3-4】求后序遍历
1339:【例3-4】求后序遍历
100 0
|
9月前
二叉树的中序遍历
二叉树的中序遍历
62 0
|
9月前
|
C++
二叉树的后序遍历(C++)
二叉树的后序遍历(C++)
58 0
|
9月前
|
Linux
求二叉树的先序遍历
求二叉树的先序遍历
|
9月前
二叉树的前、中、后序遍历的实现
二叉树的前、中、后序遍历的实现
|
JavaScript 前端开发 Java
二叉树的先序、中序、后序遍历
二叉树的先序、中序、后序遍历
182 0
二叉树的先序、中序、后序遍历