由前序、中序遍历,求二叉树的结构

代码如下:

#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。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值