题解 | #二叉排序树#

二叉排序树

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

#include<iostream>

using namespace std;

typedef struct node {
    int data;
    struct node* lchild;
    struct node* rchild;
}* BiTree, node;

void firstSearch(node* p);

int main() {
    int n;
    cin >> n;

    int* A = new int[n];
    for (int i = 0; i < n; i++)cin >> A[i];

    node* T = new node;
    if (n > 0) {
        T->data = A[0];
        T->lchild = NULL;
        T->rchild = NULL;
        cout << "-1" << endl;
    }

    for (int i = 1; i < n; i++) {
        node* p;
        node* q;
        q = T;

        while (q != NULL) {
            p = q;
            if (A[i] <= q->data)q = p->lchild;
            else q = p->rchild;
        }

        node* r = new node;
        r->data = A[i];
        r->lchild = NULL;
        r->rchild = NULL;

        if (A[i] <= p->data && p->lchild == NULL) p->lchild = r;
        else if (A[i] > p->data && p->rchild == NULL) p->rchild = r;

        cout << p->data << endl;
    }

    return 0;
}

全部评论

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务