給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/
2 3
5
輸出: [“1->2->5”, “1->3”]
解釋: 所有根節點到葉子節點的路徑爲: 1->2->5, 1->3
/**
* 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> res;
string temp;
findpath(root,temp,res);
return res;
}
void findpath(TreeNode* root,string temp,vector<string> &res)
{
if(root==nullptr)
return;
temp=temp+to_string(root->val)+"->";
//是葉子節點
if(root->left==nullptr&&root->right==nullptr)
{
temp.erase(temp.length()-2);
res.push_back(temp);
}
if(root->left!=nullptr)
findpath(root->left,temp,res);
if(root->right!=nullptr)
findpath(root->right,temp,res);
}
};