十七
十七
Published on 2022-03-05 / 155 Visits
0
0

leetcode257. 二叉树的所有路径

leetcode257. 二叉树的所有路径

class Solution {
public:
    void dfs(TreeNode* root,string path,vector<string>& ans){
        if(root){
            path+=to_string(root->val);
            if(root->left==nullptr&&root->right==nullptr){
                ans.push_back(path);
            }else{
                path+="->";
                dfs(root->left,path,ans);
                dfs(root->right,path,ans);
            }
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> ans;
        dfs(root,"",ans);
        return ans;
    }
};

Comment