#include <iostream> #include <vector> #include <sstream> using namespace std; struct TreeNode { string val; TreeNode* left; TreeNode* right; TreeNode(string x) : val(x), left(nullptr), right(nullptr) {} }; TreeNode* buildTreeHelper(const vector<string>& preorder, int& pos, const string& sep) { if (pos >= preorder.size() || preorder[pos] == sep) { ++pos; return nullptr; } string s = preorder[pos]; ++pos; TreeNode* root = new TreeNode(s); root->left = buildTreeHelper(preorder, pos, sep); root->right = buildTreeHelper(preorder, pos, sep); return root; } TreeNode* buildTree(const vector<string>& preorder, const string& sep) { int pos = 0; return buildTreeHelper(preorder, pos, sep); } void preorder1(TreeNode* root) { if (!root) return; cout << root->val << ","; preorder1(root->left); preorder1(root->right); } void inorder(TreeNode* root) { if (!root) return; inorder(root->left); cout << root->val << ","; inorder(root->right); } void postorder(TreeNode* root) { if (!root) return; postorder(root->left); postorder(root->right); cout << root->val << ","; } int main() { string sep; getline(cin, sep); vector<string> preorder; string line; getline(cin, line); stringstream ss(line); string s; while (getline(ss, s, ' ')) { preorder.push_back(s); } TreeNode* root = buildTree(preorder, sep); cout << "Preorder: "; preorder1(root); cout << endl; cout << "Inorder: "; inorder(root); cout << endl; cout << "Postorder: "; postorder(root); cout << endl; return 0; }如何避免在输出序列最后多输出一个逗号
时间: 2024-03-07 17:46:24 浏览: 139
可以在输出序列中,在每个值后面输出逗号,而在最后一个值后面不输出逗号。可以通过在遍历时判断当前节点是否是最后一个节点来实现。具体来说,在先序遍历、中序遍历和后序遍历函数中,在输出当前节点值之前,需要先判断其是否为最后一个节点,若是,则不输出逗号。可以通过比较当前节点的左右子树是否为空来判断。修改后的代码如下:
```cpp
void preorder1(TreeNode* root) {
if (!root) return;
cout << root->val;
if (root->left || root->right) cout << ",";
preorder1(root->left);
preorder1(root->right);
}
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
cout << root->val;
if (root->left || root->right) cout << ",";
inorder(root->right);
}
void postorder(TreeNode* root) {
if (!root) return;
postorder(root->left);
postorder(root->right);
cout << root->val;
if (root->left || root->right) cout << ",";
}
```
阅读全文