题解 | 二叉排序树

二叉排序树

https://www.nowcoder.com/practice/30a0153649304645935c949df7599602

#include <iostream>
using namespace std;

typedef struct Node {
    int data;
    Node* lchild, *rchild;
} Node;

void create(Node* &n, int data = -1) {
    n = new Node;
    n->data = data;
    n->lchild = n->rchild = NULL;
}

void insert(Node* head, int data) {
    if (head->data < 0) {
        cout << head->data << endl;
        head->data = data;
        return;
    }
    if (data < head->data) {
        if (head->lchild == NULL) {
            cout << head->data << endl;
            Node* Temp;
            create(Temp, data);
            head->lchild = Temp;
        } else {
            insert(head->lchild, data);
        }
    } else {
        if (head->rchild == NULL) {
            cout << head->data << endl;
            Node* Temp;
            create(Temp, data);
            head->rchild = Temp;
        } else {
            insert(head->rchild, data);
        }
    }
}

int main() {
    int n, data;
    Node* head;
    create(head);
    while (cin >> n) {
        while(n-- > 0){
            cin >> data;
            insert(head, data);
        }
    }
    return 0;
}

全部评论

相关推荐

浩浩没烦恼:一二面加起来才一个小时? 我一面就一个小时多了
点赞 评论 收藏
分享
10-10 11:38
已编辑
湖南理工大学 Java
小浪_Coding:多沟通叭, 公式简历+学历一般的话难找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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