题解 | #二叉搜索树#先递归建树,再递归判断。
二叉搜索树
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; }