1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { public: TreeNode* str2tree(string s) { s += '('; stack<TreeNode*> stk; TreeNode dummy_root(0); stk.push(&dummy_root); for (int b = 0, i = s.find_first_of("()"); i != string::npos; b = i + 1, i = s.find_first_of("()", b)) { TreeNode *x = nullptr; string num = s.substr(b, i - b); if (!num.empty()) { x = new TreeNode(stoi(num)); } if (!stk.top()->left) { stk.top()->left = x; } else if (!stk.top()->right) { stk.top()->right = x; } if (x) { stk.push(x); } if (s[i] == ')') { stk.pop(); } } return dummy_root.left; } };
|