题目:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
第一次提交
first,I can’t do it, after reference others,
then do,but much wrong:
//2018/12/24 first i can't
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<string> re;
void doit(TreeNode* root, string s)
{
if((root->left == NULL) && (root->right == NULL))
{
s = s + "->" + to_string(root->val);
re.push_back(s);
return;
}
if(root->left)
{
s = s + "->" + to_string(root->val);
doit(root->left,s);
}
if(root->right)
{
s = s + "->" + to_string(root->val); //there wrong;
doit(root->right,s);
}
}
public:
vector<string> binaryTreePaths(TreeNode* root)
{
if(root == NULL)
return re;
if((root->left == NULL) && (root->right == NULL))
{
string s;
s = s + to_string(root->val);
re.push_back(s);
}
if(root->left)
{
string s;
s = s + to_string(root->val);
doit(root->left,s);
}
if(root->right)
{
string s;
s = s + to_string(root->val);
doit(root->right,s);
}
return re;
}
};
then
Input:
[1,2,3,5,6]
Output:
["1->2->5","1->2->2->6","1->3"]
Expected:
["1->2->5","1->2->6","1->3"]
第二次提交
//2018/12/24 first i can't
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<string> re;
void doit(TreeNode* root, string s)
{
if((root->left == NULL) && (root->right == NULL))
{
s = s + "->" + to_string(root->val);
re.push_back(s);
return;
}
s = s + "->" + to_string(root->val);
if(root->left)
{
doit(root->left,s);
}
if(root->right)
{
doit(root->right,s);
}
}
public:
vector<string> binaryTreePaths(TreeNode* root)
{
if(root == NULL)
return re;
string s = to_string(root->val);
if((root->left == NULL) && (root->right == NULL))
{
re.push_back(s);
}
if(root->left)
{
doit(root->left,s);
}
if(root->right)
{
doit(root->right,s);
}
return re;
}
};
right;