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 38 39 40 41 42 43 44
|
class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<int> path; vector<string> result; if (root == NULL) return result; traversal(root, path, result); return result; } void traversal(TreeNode* cur, vector<int> &path, vector<string> &result){ path.push_back(cur->val); if (cur->left == NULL && cur->right == NULL){ string sPath; for (int i = 0; i < path.size() - 1; ++i){ sPath += to_string(path[i]); sPath += "->"; } sPath += to_string(path[path.size() - 1]); result.push_back(sPath); return; } if (cur->left) { traversal(cur->left, path, result); path.pop_back(); } if (cur->right) { traversal(cur->right, path, result); path.pop_back(); } } };
|