首页 > 其他 > 详细

层序中序建树代码

时间:2020-04-08 17:04:43      阅读:48      评论:0      收藏:0      [点我收藏+]
#include "iostream"
using namespace std;
struct node {
    int val;
    node *left, *right;
    node(int v):val(v), left(NULL), right(NULL){}
} *root = NULL;
int level[] = {1, 2, 3, 4, 5};
int in[] = {4, 2, 1, 3, 5};

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;
}

void pre_order(node *n) {
    if(!n) return;
    printf("%d ", n->val);
    pre_order(n->left);
    pre_order(n->right);
}
int main(int argc, char const *argv[])
{
    root = build(0, 4, 0, 4);
    pre_order(root);
    return 0;
}

层序中序建树代码

原文:https://www.cnblogs.com/littlepage/p/12660395.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!