C++代码: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if (!root) return ans; vector<string> left = binaryTreePaths(root->left), right = binaryTreePaths(root->right); ans.insert(ans.end(), left.begin(), left.end()); ans.insert(ans.end(), right.begin(), right.end()); if (!ans.size()) ans.push_back(to_string(root->val)); else { for (string &s : ans) { s = to_string(root->val) + "->" + s; } } return ans; }
题目如下:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]