题解 | #二叉搜索树#

二叉搜索树

https://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b

#include <iostream>
using namespace std;
struct TreeNode {
    int val;
    TreeNode* left, *right;
    TreeNode() : left(nullptr), right(nullptr){}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* init(TreeNode* r, int x) {
    if (!r) {
        r = new TreeNode(x);
        return r;
    }
    if (r ->val < x)
        r -> left = init(r -> left, x);
    else
        r -> right = init(r -> right, x);
    return r;
}
bool cmp(TreeNode* r1, TreeNode* r2) {
    if (!r1 && !r2) return true;
    if (!r1 || !r2) return false;
    if (r1 -> val != r2 -> val) return false;
    return cmp(r1 -> left, r2 -> left) && cmp(r1 -> right, r2 -> right);
}
int main() {
    int n;
    string s;
    while (cin >> n && n) { // 注意 while 处理多个 case
        cin >> s;
        TreeNode* r = nullptr;
        // cout << r<< endl;
        for (auto c : s) r = init(r, c - '0');
        while (n --) {
            cin >> s;
            TreeNode* t = nullptr;
            for (auto c : s) t = init(t, c - '0');
            if(cmp(r, t)) cout << "YES\n";
            else cout << "NO\n";
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务