题解 | 二叉排序树

二叉排序树

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

#include <iostream>
using namespace std;

struct tree {
    int data;
    tree* parent;
    tree* left=NULL;
    tree* right=NULL;
};

void build(tree*& root, tree* parent, int x) {
    if (root == NULL) {
        root = new tree;
        root->data = x;
        root->parent = parent;
        if (root->parent == NULL)cout << -1 << endl;
        else cout << root->parent->data << endl;
        return;
    }
    if (x < root->data)
        build(root->left, root, x);
    else
        build(root->right, root, x);

}
int main() {
    int n;
    while (cin >> n) { // 注意 while 处理多个 case
        tree* root=NULL;
        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            build(root, NULL, x);
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

03-19 10:07
已编辑
广东药科大学 Java
Yki_:你倒是进一个面啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务