Description:
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"]
Code:
void allPath(TreeNode*root, vector<string>&result, vector<int>&path) { if (root==NULL) return ; path.push_back(root->val); if (root->left==NULL && root->right==NULL) { //注意这里要用ostringstream将字符串写到流中去,然后用str()函数返回字符串 ostringstream sstr; for (int i = 0; i < path.size()-1; ++i) sstr << path[i]<<"->"; sstr<<path[path.size()-1]; result.push_back(sstr.str()); } else { if (root->left) allPath(root->left, result, path); if (root->right) allPath(root->right, result, path); } path.pop_back(); } vector<string> binaryTreePaths(TreeNode* root) { vector<string>result; vector<int>path; allPath(root, result,path); return result; }