- Binary Tree Paths
Easy
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/
2 3
5
Output: [“1->2->5”, “1->3”]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
class Solution {
public:
void find(vector<string>& res, TreeNode* root, string t)
{//t表示当前路径上已经存储好的结点顺序
if(!root->left&&!root->right)
{
res.push_back(t+"->"+to_string(root->val));
return;
}
if(root->left) find(res,root->left,t+"->"+to_string(root->val));
if(root->right) find(res,root->right,t+"->"+to_string(root->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>ans;
if(!root) return ans;
if(!root->left&&!root->right) ans.push_back(to_string(root->val));
if(root->left) find(ans,root->left, to_string(root->val));
if(root->right) find(ans,root->right,to_string(root->val));
return ans;
}
};