Title Source: http://dsalgo.openjudge.cn/binarytree/8/ 8: Rebuilding the binary tree
Total time limit: 1000ms memory limit: 65536kB
Description
Given a binary tree's pre-sequence traversal and the result of the middle sequence traversal, its post-order traversal is obtained.
input
The input may have more than one group, ending with EOF.
Each set of inputs contains two strings, respectively, for the tree's pre-order traversal and the middle sequence traversal. Each string contains only uppercase letters and is distinct from each other.
Output
For each set of inputs, a row is used to output its post-order traversal results.
Sample Input
DBACEGF ABCDEFG
Bcad Cbad
Sample Output
Acbfged
Cdab
-----------------------------------------------------
Thinking of solving problems
Recursive, first locating the root node and then slicing the Saozi right subtree
Note the application of the String.substr () method
-----------------------------------------------------
Code
#include <iostream>
#include <string>
using namespace std;
String Postorder (string mid, String Pre) //input preorder string and inorder string, output Postorder string
{
if (pre.length () = = 1) return pre; If preorder has only one character then preorder = Inorder = Postorder
Else if (pre.length () ==0) return ""; Returns an empty string if preorder is empty/
/This avoids the existence of a left/right subtree discussion
else
{
size_t root = Mid.find (pre.at (0)); The root node of the tree
return Postorder (Mid.substr (0,root), Pre.substr (1,root)) //First left subtree
+ postorder (MID.SUBSTR ( root+1), Pre.substr (root+1)) + pre.at (0);//Right Sub-tree, last root node
//Note: Str.substr (str.size ()) returns an empty string without throwing an exception.
}
}
int main ()
{
string Pre, Mid, post;//s1 to preorder traversal S2 to inorder traversal while
(cin > > Pre >> mid)
{
Post=postorder (Mid, pre);
cout << post << Endl;
}
return 0;
}