二叉树的所有路径
/**
* 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;
string temp="";
if(root==NULL)
return result;
binaryTree(root,temp,result);
return result;
}
void binaryTree(TreeNode* root,string temp,vector<string>& result)
{
if(root==NULL)
return;
if(root->right==NULL&&root->left==NULL)
{
temp=temp+to_string(root->val);
result.push_back(temp);
return;
}
temp=temp+to_string(root->val);
temp=temp+"->";
binaryTree(root->left,temp,result);
binaryTree(root->right,temp,result);
}
};
为什么不用回溯:
原因是对于每次遍历的结果我们其实都是存放在string中,这样就相当于复制了