0257.cpp (722B)
1 class Solution { 2 public: 3 vector<string> binaryTreePaths(TreeNode *root) { 4 if (!root) return {}; 5 6 vector<string> res; 7 stack<pair<TreeNode *, string>> st; 8 st.push({root, to_string(root->val)}); 9 while (!st.empty()) { 10 TreeNode *root = st.top().first; 11 string s = st.top().second; 12 st.pop(); 13 if (!root->left && !root->right) 14 res.push_back(s); 15 else { 16 s += "->"; 17 if (root->left) st.push({root->left, s + to_string(root->left->val)}); 18 if (root->right) st.push({root->right, s + to_string(root->right->val)}); 19 } 20 } 21 return res; 22 } 23 };