题解 | #二叉搜索树#先递归建树,再递归判断。

二叉搜索树

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

#include <iostream>
using namespace std;
struct TreeNode {
    char val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(char c) : val(c), left(nullptr), right(nullptr) {}
    ~TreeNode() {
        delete left, right;
    }
};
TreeNode *insertTree(TreeNode *root, char c) {
    if (root == nullptr) return new TreeNode(c);
    if (c < root->val) root->left = insertTree(root->left, c);
    else root->right = insertTree(root->right, c);
    return root;
}
bool isSameTree(TreeNode *p, TreeNode *q) {
    if (p == nullptr && q == nullptr) return true;
    if (p == nullptr || q == nullptr) return false;
    return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
int main() {
    int n;
    string s;
    cin >> n >> s;
    TreeNode *root1 = nullptr;
    for (char c: s) root1 = insertTree(root1, c);
    while (n--) {
        string t;
        cin >> t;
        TreeNode *root2 = nullptr;
        for (char c: t) root2 = insertTree(root2, c);
        if (isSameTree(root1, root2)) cout << "YES" << endl;
        else cout << "NO" << endl;
        delete root2;
    }
    delete root1;
    return 0;
}

全部评论

相关推荐

10-21 23:48
蚌埠坦克学院
csgq:可能没hc了 昨天一面完秒挂
点赞 评论 收藏
分享
11-08 13:58
门头沟学院 Java
程序员小白条:竟然是蓝桥杯人才doge,还要花钱申领的offer,这么好的公司哪里去找
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务