#23461: C++ 解法(簡潔)


asdfghjkl42045@gmail.com (聖冰如焰)

學校 : 不指定學校
編號 : 89298
來源 : [163.19.240.54]
最後登入時間 :
2020-11-22 10:16:42
d526. Binary Search Tree (BST) | From: [163.19.240.54] | 發表日期 : 2020-11-19 14:48

#include <bits/stdc++.h>

/*#pragma GCC optimize ("O3") // 加速

#pragma loop_opt (on)*/

using namespace std;

 

struct B {

    B *L, *R;

    int I;

};

B* Add(B* tree,int n) { // 新增

    if (tree == NULL) { // 創建

        tree = new B();

        tree->I = n;

        tree->L = NULL;

        tree->R = NULL;

    }

    else if (tree->I < n) tree->R = Add(tree->R, n);

    else tree->L = Add(tree->L, n);

    return tree;

}

string IO(B* tree) {

    if (tree == NULL) return "";

    return to_string(tree->I) + " " + IO(tree->L) + IO(tree->R);

}

 

int main() {

    ios::sync_with_stdio(0); cin.tie(0);

    int n, m;

    while (cin >> n) {

        B *tree = NULL;

        for (int i = 0; i < n; i++) {

            cin >> m;

            tree = Add(tree, m);

        }

        cout << IO(tree) << "\n";

    }

    return 0;

}

 
ZeroJudge Forum