0606.cpp (722B)
1 class Solution { 2 public: 3 string tree2str(const TreeNode *root) { 4 stack<const TreeNode *> stack; 5 stack.push(root); 6 string res = ""; 7 8 while (!stack.empty()) { 9 const TreeNode *temp = stack.top(); 10 stack.pop(); 11 if (temp == nullptr) 12 res += ')'; 13 else { 14 res += '(' + to_string(temp->val); 15 stack.push(nullptr); 16 17 if (temp->right) stack.push(temp->right); 18 19 if (temp->left) 20 stack.push(temp->left); 21 else if (temp->right) 22 res += "()"; 23 } 24 } 25 return res.substr(1, res.size() - 2); 26 } 27 };