【题目】
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5All root-to-leaf paths are:
["1->2->5", "1->3"]【解答】
最直接的方法就是 DFS
【答案】
/**
* 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:
void dfs(TreeNode* root,string temp,vector<string> &v)
{
string s;
s=to_string(root->val);
if (temp=="")
{
temp=s;
}
else
temp=temp+"->"+s;
if (root->left==NULL && root->right==NULL)
{
v.push_back(temp);
}
else
{
if (root->left)
{
dfs(root->left,temp,v);
}
if (root->right)
dfs(root->right,temp,v);
}
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> v;
if (root==NULL) //空树
return v;
string temp="";
dfs(root, temp, v);
return v;
}
};