回復 1# may - //#include <iostream>
- //#include <vector>
- //#include <algorithm>
- #include <bits/stdc++.h>
- using namespace std;
- // 定義二元樹節點結構
- struct TreeNode {
- char value; // 節點的值
- TreeNode* left; // 左子節點
- TreeNode* right; // 右子節點
-
- TreeNode(char val) : value(val), left(nullptr), right(nullptr) {}
- };
- // 根據陣列建立二元樹
- TreeNode* buildTree(const vector<string>& nodes, int index) {
- if (index >= nodes.size() || nodes[index] == "") {
- return nullptr; // 如果超出範圍或是空節點,返回空
- }
-
- TreeNode* node = new TreeNode(nodes[index][0]); // 創建節點
- node->left = buildTree(nodes, 2 * index + 1); // 左子節點
- node->right = buildTree(nodes, 2 * index + 2); // 右子節點
- return node;
- }
- // 中序走訪 (Inorder traversal)
- void inorderTraversal(TreeNode* root, string& result) {
- if (root == nullptr) {
- return;
- }
- inorderTraversal(root->left, result); // 遍歷左子樹
- result += root->value; // 訪問根節點
- inorderTraversal(root->right, result); // 遍歷右子樹
- }
- // 尋找所有葉節點
- void findLeafNodes(TreeNode* root, vector<char>& leaves) {
- if (root == nullptr) {
- return;
- }
- if (root->left == nullptr && root->right == nullptr) {
- leaves.push_back(root->value); // 如果是葉節點,加入葉節點列表
- }
- findLeafNodes(root->left, leaves); // 查找左子樹
- findLeafNodes(root->right, leaves); // 查找右子樹
- }
- int main() {
- string input;
- getline(cin, input); // 讀取整行輸入
-
- // 將字串根據逗號分割成陣列
- vector<string> nodes;
- size_t pos = 0;
- while ((pos = input.find(',')) != string::npos) {
- nodes.push_back(input.substr(0, pos));
- input.erase(0, pos + 1);
- }
- nodes.push_back(input); // 添加最後一個節點(可能是空的)
- // 根據輸入的陣列建立二元樹
- TreeNode* root = buildTree(nodes, 0);
- // 1. 中序走訪並輸出結果
- string inorderResult;
- inorderTraversal(root, inorderResult);
- cout << inorderResult << endl;
- // 2. 找出葉節點並按照字母順序排序
- vector<char> leafNodes;
- findLeafNodes(root, leafNodes);
- sort(leafNodes.begin(), leafNodes.end()); // 排序葉節點
- for (char leaf : leafNodes) {
- cout << leaf;
- }
- cout << endl;
- return 0;
- }
複製代碼 -------------------------------------------------
程式解釋:
TreeNode結構:定義了二元樹的節點,每個節點包含value(節點值)、left(左子樹指標)和right(右子樹指標)。
buildTree函數:根據傳入的字串陣列來遞歸建立二元樹,使用完全二元樹的索引規則。
inorderTraversal函數:進行中序走訪(左-根-右),並將走訪的結果保存在字串中。
findLeafNodes函數:尋找葉節點,葉節點的定義是左右子樹均為nullptr的節點,並將這些葉節點存入leaves向量。
主程式:首先讀取並解析輸入的字串,建立二元樹,然後進行中序走訪並輸出所有節點,接著尋找葉節點並按字母順序輸出。
範例輸入 1:
mathematica
A,B,C,D,,E,F
範例輸出 1:
DBAECF
DEF
範例輸入 2:
mathematica
A,B,C,D,E,,,,,F,G
範例輸出 2:
DBFEGAC
CDFG
總結:
這段程式碼解決了二元樹的建立、走訪以及葉節點的排序輸出問題,並且利用遞歸進行樹的遍歷與操作。
--------------------------------------------
測資
測資00:
輸入:
A,B,C,D,,E,F
輸出:
DBAECF
DEF
測資 01:
輸入:
A,B,C,D,E,,,,,F,G
輸出:
DBFEGAC
CDFG
測資 02:
輸入:
A,B,C,D,E,F,G,H,I,J
輸出:
DBEAFCGHIJ
DEFGHIJ
測資 03:
輸入:
X,Y,Z,,A,B,,C,D
輸出:
YZXABCD
ABC
測資 04:
輸入:
M,N,O,P,Q,R,S,T,U
輸出:
PNMOQRSUT
PQR
這些測資涵蓋了各種情境,包括:
樹形結構中有空節點(例如空字串 "")。
節點數量較多或較少的情況。
測試程式對不同排列組合的處理能力。 |