小米-2020-秋招-软件开发笔试
笔试
打印二叉树
一个重建二叉树+中序遍历打印的问题
麻烦的是C++中没有现成的替换字符串中子字符串的函数
#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; struct TreeNode { char val; TreeNode* leftChild; TreeNode* rightChild; TreeNode(char _val) :val(_val), leftChild(nullptr), rightChild(nullptr) {} }; TreeNode* buildTree(string input) { stack<TreeNode*> nodes; // 将字符串转为一个字符数组 vector<char> nums; nums.resize(input.size()); nums.assign(input.begin(), input.end()); for (char ch : nums) { if (ch >= '0' && ch <= '9') { TreeNode* node = new TreeNode(ch); nodes.push(node); } else if (ch == ')') { TreeNode* right = nodes.top(); nodes.pop(); TreeNode* left = nodes.top(); nodes.pop(); nodes.top()->leftChild = left->val == '0' ? nullptr : left; nodes.top()->rightChild = right->val == '0' ? nullptr : right; } } return nodes.top(); } void printTree(TreeNode* root) { if (!root) return; printTree(root->leftChild); cout << root->val; printTree(root->rightChild); } int main() { string _input; getline(cin, _input); string::size_type pos = 0; // string::npos表示直至字符串结尾 while ((pos = _input.find("(,")) != string::npos) { _input.replace(pos, 2, "(0,"); } while ((pos = _input.find(",)")) != string::npos) { _input.replace(pos, 2, ",0)"); } TreeNode* root = buildTree(_input); printTree(root); return 0; } // 1(2(3,4(,5)),6(7,))
小米之家购物
很明显是个背包问题
本文作者:YaosGHC
本文链接:https://www.cnblogs.com/yaocy/p/16692642.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步