题目描述:给定一个二叉树,返回所有从根节点到叶子节点的路径。
解题思路:分别递归左子树和右子树。
代码:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>res;
if(root==nullptr) return res;
binaryTreePaths(root,res,"");
return res;
}
void binaryTreePaths(TreeNode*root,vector<string>&res,string path){
path+=to_string(root->val);
if(root->left==nullptr&&root->right==nullptr){
res.push_back(path);
return;
}
if(root->left) binaryTreePaths(root->left,res,path+"->");
if(root->right) binaryTreePaths(root->right,res,path+"->");
}
};