题解 | #二叉排序树#

二叉排序树

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")

全部评论

相关推荐

点赞 评论 收藏
分享
千千倩倩:简历问题有点多,加v细聊
点赞 评论 收藏
分享
09-21 21:14
门头沟学院
否极泰来来来来:和他说:这里不好骂你,我们加个微信聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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