题解 | #二叉排序树#

二叉排序树

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

#include <iostream>
using namespace std;
const int N = 101;

struct Node{
    int data;
    Node* left;
    Node* right;
    Node(int x):data(x), left(NULL), right(NULL){}
};

Node* insert(Node* root, int x){
    if(root == NULL){
        root = new Node(x);
    }
    else if(x < root->data){
        root->left = insert(root->left, x);
    }
    else if(x > root->data){
        root->right = insert(root->right, x);
    }
    else if(x == root->data){}//不做处理

    return root;
}

void preOrder(Node* root){
    if(root != NULL){
        cout << root->data << " ";
        preOrder(root->left);
        preOrder(root->right);
    }
}

void inOrder(Node* root){
    if(root != NULL){
        inOrder(root->left);
        cout << root->data << " ";
        inOrder(root->right);
    }
}

void postOrder(Node* root){
    if(root != NULL){
        postOrder(root->left);
        postOrder(root->right);
        cout << root->data << " ";
    }
}


int main() {
    int n, x;
    while(cin >> n){
        Node* root = NULL;
        while(n --){
            cin >> x;
            root = insert(root, x);
        }
        preOrder(root);
        cout << endl;
        inOrder(root);
        cout << endl;
        postOrder(root);
        cout << endl;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-20 20:30
工作没了,落户没了,什么都没了
梦想是成为七海千秋:是因为什么原因呀,如果是因为导师恶意卡你就和他爆了
点赞 评论 收藏
分享
震撼沃玛一整年:查看图片
点赞 评论 收藏
分享
牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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