给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
先访问根节点。然后递归遍历左子树和右子树。遇到叶节点则保存路径。
```
vector binaryTreePaths(TreeNode* root) {
vector res;
if(root==NULL)
return res;
findPath(root,res,to_string(root->val));
return res;
}
void findPath(TreeNode* root,vector& res,string s){
if(!root->left && !root->right){
res.push_back(s);
return;
}
if(root->left){
findPath(root->left,res,s+"->"+to_string(root->left->val));
}
if(root->right){
findPath(root->right,res,s+"->"+to_string(root->right->val));
}
}
```
Copyright © 2018 成都猎维科技有限公司 版权所有