代码如下:
#include "stdafx.h"
#include <string>
using namespace std;
string pre = "alicloud";
string in = "illcaudo";
typedef struct Node{
char ch;
Node * left, *right;
}*TreeNode;
int rebuild( TreeNode & root, string pre, string in ){
if( pre.length() == 0 ){
root = 0;
return 0;
}
char ch = pre[0];
int indx = in.find( ch );
string left_in = in.substr( 0, indx);
string right_in = in.substr(indx+1);
pre.erase(0, 1);
string left_pre = pre.substr( 0, left_in.length() );
string right_pre = pre.substr( left_in.length() );
root = new Node;
root->ch = ch;
rebuild( root->left, left_pre, left_in );
rebuild( root->right, right_pre, right_in);
return 0;
}
void pre_travel(TreeNode root){
if( NULL == root ) return;
printf("%c", root->ch);
pre_travel( root->left );
pre_travel( root->right);
}
回顾 string 的用法:
str.length() : 字符串占用字节的长度, 与str.size()一样,使用length()是为了兼容c。vector就没有length()。
str.remove( pos, 1 ): 删除pos处的字符,字符串整体前移。
str.substr( pos, len ): str的子串,从pos起长度为len,pos在0到len-1之间。
str.substr( pos ): str的子串,从pos一直到末尾。
str.find( ch ): str中ch的位置,若找到则返回值为 0到 len-1之间,否则返回无符号的最大数0xFFFFFFFF,即-1对应的无符号数,也是string::npos。