题目:
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"]
分析:让你对一棵树进行遍历,找出所有从跟节点到到叶子节点的路径,每条路径作为一个string保存到vector < string> 里面。只是对树的递归遍历,但是令人吃惊的是这道题在leetcode上只有 24%的通过率。
代码:
/**
* 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 {
public:
vector<string> res ;
void getPath(TreeNode* root,string s)
{
if(root->right == NULL && root->left == NULL)
res.push_back(s);
if(root->left!=NULL)
{
string s1 ;
s1 = s + "->" + int2string(root->left->val);
cout << s1 << endl;
getPath(root->left,s1);
}
if(root->right!=NULL)
{
string s1 ;
s1 = s + "->" + int2string(root->right->val);
cout << s1 << endl;
getPath(root->right,s1);
}
}
string int2string(int Number)
{
string Result;
stringstream convert;
convert << Number;
Result = convert.str();
return Result;
}
vector<string> binaryTreePaths(TreeNode* root) {
string s;
if(root != NULL)
{
s = to_string(root->val);
getPath(root,s);
}
cout << "out if " << endl;
return res;
}
};