题解 | #二叉排序树#

二叉排序树

https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct node {
    int val;
    struct node* left, *right;
}* bittree, node;

bittree build(bittree& t, bittree node) {
    if (t == NULL) {
        return node;
    }
    if (t->val > node->val) {
        t->left = build(t->left, node);
    } else if (t->val < node->val) {
        t->right = build(t->right, node);
    }
    return t;
}

void prepost(bittree t) {
    if (t != NULL) {
        cout << t->val << " ";
        prepost(t->left);
        prepost(t->right);
    }
}

void midpost(bittree t) {
    if (t != NULL) {
        midpost(t->left);
        cout << t->val << " ";
        midpost(t->right);
    }
}

void postpost(bittree t) {
    if (t != NULL) {
        postpost(t->left);
        postpost(t->right);
        cout << t->val << " ";
    }
}

int main() {
    int n;
    while(cin >> n){
    int temp;
    bittree t = NULL;
    for (int i = 0; i < n; i++) {
        cin >> temp;
        bittree t_node = (bittree)malloc(sizeof(node));
        t_node->val = temp;
        t_node->left = NULL;
        t_node->right = NULL;
        t = build(t, t_node);
    }
    prepost(t);
    cout << endl;
    midpost(t);
    cout << endl;
    postpost(t);
    cout << endl;
    }
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务