还不快抢沙发

添加新评论

给定一个二叉树,返回从根节点到叶节点的所有路径。 例如,给定以下二叉树: ``` 1 / \ 2 3 \ 5 ``` 所有根到叶路径是: ``` ["1->2->5", "1->3"] ``` 解答: ```` vector binaryTreePaths(TreeNode* root) { vector collection; vector res; vector chain; binaryTreePathsRecur(root, collection, chain); for (auto& i : collection) { res.push_back(convertVectorToString(i)); } return res; } void binaryTreePathsRecur(TreeNode* root, vector& collection, vector& chain) { if (!root) { return; } if (!root->left && !root->right) { vector copy(chain); copy.push_back(root->val); collection.push_back(copy); return; } chain.push_back(root->val); binaryTreePathsRecur(root->left, collection, chain); binaryTreePathsRecur(root->right, collection, chain); chain.pop_back(); } string convertVectorToString(vector nums) { string res; for (auto i = nums.begin(); i != nums.end(); i++) { if (i == nums.end() - 1) { res += to_string(*i); } else { res += to_string(*i) + "->"; } } return res; } ````