Leetcode 257 二叉树的所有路径(给定一个二叉树,返回所有从根节点到叶子节点的路径)

搜索到叶子节点时往答案中添加。标准的DFS
 

class Solution {
public:
    vector<string> res;
    vector<string> binaryTreePaths(TreeNode* root) {
        string s;
        dfs(root,s);
        return res;

    }
    
    void dfs(TreeNode* root, string s){
        if(root==NULL){
            return;
        }
        if(root->left==NULL&&root->right==NULL){
            s+= to_string(root->val);
            res.push_back(s);
            return;
        }
        s+= to_string(root->val) + "->";
        dfs(root->left,s);
        dfs(root->right,s);
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108412322