1、原题如下:
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”]
2、解题如下:
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(!root) return result;
Binarytreesearch(result,to_string(root->val),root);
return result;
}
void Binarytreesearch(vector<string>& result,string temp,TreeNode* root){
if(!root->left&&!root->right)
{
result.push_back(temp);
return;
}
if(root->left)
{
Binarytreesearch(result,temp+"->"+to_string(root->left->val),root->left);
}
if(root->right)
{
Binarytreesearch(result,temp+"->"+to_string(root->right->val),root->right);
}
}
};
3、总结
开始笔者将这一段
if(root->left)
{
Binarytreesearch(result,temp+"->"+to_string(root->left->val),root->left);
}
if(root->right)
{
Binarytreesearch(result,temp+"->"+to_string(root->right->val),root->right);
}
写成了如下:
if(root->left)
{
temp+=+"->"+to_string(root->left->val);
Binarytreesearch(result,temp,root->left);
}
if(root->right)
{
temp+="->"+to_string(root->right->val);
Binarytreesearch(result,temp,root->right);
}
结果的输出如下:
能想出来原因么?(Hint:think about how can we get 3 nodes but not 2)