题解 | #二叉排序树#

二叉排序树

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

#include <cstddef>
#include <iostream>
using namespace std;
struct node {
    int data;
    node* leftChild;
    node* rightChild;
    node(int a) {
        data = a;
        leftChild = NULL;
        rightChild = NULL;
    }
};
node* insert(node* root, int a) {
    if (root == NULL) {
        return new node(a);
    }
    if (a < root->data) root->leftChild = insert(root->leftChild,  a);
    else if (a > root->data)root->rightChild = insert(root->rightChild,  a);
    return root;
}
void  preOder(node* root) {
    if (root == NULL) return;
    cout << root->data << ' ';
    preOder(root->leftChild);
    preOder(root->rightChild);
}
void  inOder(node* root) {
    if (root == NULL) return;

    inOder(root->leftChild);
    cout << root->data << ' ';
    inOder(root->rightChild);
}
void  postOder(node* root) {
    if (root == NULL) return;
    postOder(root->leftChild);
    postOder(root->rightChild);
    cout << root->data << ' ';
}
int main() {
    int n;
    while (cin >> n) { // 注意 while 处理多个 case

        node* root = NULL;
        while (n--) {
            int a;
            cin >> a;
            root = insert(root, a);
        }
        preOder(root);
        cout<<endl;
        inOder(root);
        cout<<endl;
        postOder(root);
        cout<<endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

感觉怪怪的,有时候莫名其妙说我适合硬件给我干到硬件开发去
嵌入式的小白:你这主修课程,和项目,都偏硬件啊
点赞 评论 收藏
分享
09-18 20:41
门头沟学院 Java
要个offer怎么这...:哈哈哈哈哈哈,我也拿了0x10000000个offer,秋招温啦啦啦,好开心
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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