4种建树问题

4种建树问题

前中建树

void pre(int root, int start, int end) {
    if(start > end) return ;
    int i = start;
    while(i < end && in[i] != post[root]) i++;
    printf("%d ", post[root]);
    pre(root - 1 - end + i, start, i - 1);
    pre(root - 1, i + 1, end);
}

后中建树

void post(int root, int start, int end) {
    if(start > end) 
        return ;
    int i = start;
    while(i < end && in[i] != pre[root]) i++;
    post(root + 1, start, i - 1);
    post(root + 1 + i - start, i + 1, end);
    printf("%d ", pre[root]);
}

层中建树

node* build(int level_left, int level_right, int in_left, int in_right) {
    if(in_left > in_right) return NULL;
    int k, flag = 0;
    while(level_left <= level_right) {
        for(k = in_left; k <= in_right; k++)
            if(in[k] == level[level_left]) {
                flag = 1;
                break;
            }
        if(flag) break;
        level_left++;
    }
    node *n = new node(in[k]);
    n->left = build(level_left + 1, level_right, in_left, k - 1);
    n->right = build(level_left + 1, level_right, k + 1, in_right);
    return n;
}

先序后序

node *build(int pre_l, int pre_r, int post_l, int post_r) {
    if(pre_l > pre_r) return NULL;
    if(pre_l == pre_r) return new node(pre[pre_l]);
    node *n = new node(pre[pre_l]);
    int k = post_l;
    while(k < post_r && post[k] != pre[pre_l + 1]) k++;
    n->left = build(pre_l + 1, pre_l + 1 + k - post_l, post_l , k - 1);
    n->right = build(pre_l + 1 + k - post_l + 1, pre_r, k + 1, post_r - 1);
    return n;
}
posted @ 2020-05-01 16:14  SteveYu  阅读(236)  评论(0编辑  收藏  举报