給定字串構建二叉排序樹(BST)。輸入 n 個查詢字串,判斷每個字串構建的 BST 是否與原樹同構(前序或後序遍歷相同即可)。n=0 結束。
#include#include using namespace std; struct Node { char data; Node *l, *r; Node(char c) : data(c), l(nullptr), r(nullptr) {} }; void insert(Node* &root, char key) { if (!root) { root = new Node(key); return; } if (key < root->data) insert(root->l, key); else insert(root->r, key); } void preorder(Node* root, string& s) { if (!root) return; s += root->data; preorder(root->l, s); preorder(root->r, s); } void postorder(Node* root, string& s) { if (!root) return; postorder(root->l, s); postorder(root->r, s); s += root->data; } int main() { int n; while (cin >> n && n) { string orig; cin >> orig; Node* root = nullptr; for (char c : orig) insert(root, c); string pre, post; preorder(root, pre); postorder(root, post); while (n--) { string q; cin >> q; if (q == orig || q == pre || q == post) cout << "YES\n"; else cout << "NO\n"; } } return 0; }
此題考察 BST 構建與遍歷,邏輯直觀易實現。