void binaryTreePathsHelper(string s,vector<string>& result,TreeNode* node) { if(node == 0) { return; } if(node->left == 0 && node->right == 0) { s += to_string(node->val); result.push_back(s); return; } s += to_string(node->val) + "->"; binaryTreePathsHelper(s,result,node->left); binaryTreePathsHelper(s,result,node->right); }
void binaryTreePathsHelper(TreeNode* root, vector<int> solution, vector<string>& result ) { if (!root) return; solution.push_back(root->val); //meet the leaf node, shape a path into the result if (root->left==NULL && root->right==NULL){ if(solution.size()>0){ stringstream ss; for(int i=0; i<solution.size(); i++){ ss << solution[i] << (i<solution.size()-1 ? "->":""); } result.push_back(ss.str()); } return; } binaryTreePathsHelper(root->left, solution, result); binaryTreePathsHelper(root->right, solution, result); }
vector<string> binaryTreePaths(TreeNode* root) { vector<string> ret; binaryTreePathsHelper("",ret,root); return ret; }
vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; vector<int> solution; binaryTreePathsHelper(root, solution, result); return result; }