LeetCode 257. Binary Tree Paths
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<string> binaryTreePaths(TreeNode* root) { 13 vector<string> res; 14 if(!root) return res; 15 help(root,res,""); 16 return res; 17 18 } 19 20 void help(TreeNode* root, vector<string>& res, string cur){ 21 if(!root) return; 22 stringstream ss; 23 ss<<root->val; 24 string tmp; 25 ss>>tmp; 26 if(cur != "") cur = cur + "->" + tmp; 27 else cur = tmp; 28 if(!root->left && !root->right){ 29 res.push_back(cur); 30 return; 31 } 32 help(root->left,res,cur); 33 help(root->right,res,cur); 34 35 } 36 };
注意应该判断cur是否为空。否则结果会是 "->1->2".