码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 257. Binary Tree Paths

时间:2016-03-02 22:03:17      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

 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".

LeetCode 257. Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/co0oder/p/5236532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!