LeetCode 257. 二叉树的所有路径 解答

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

说明: 叶子节点是指没有子节点的节点。

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(!root) return res;
        string tmp="";
        dfs(root,tmp,res);
        return res;
    }
    
    void dfs(TreeNode* root, string tmp, vector<string>&res){
        if(tmp == "")
            tmp = to_string(root->val);
        else
            tmp = tmp + "->" + to_string(root->val);
        if(!root->left&&!root->right) 
           res.push_back(tmp);
        if(root->left) 
           dfs(root->left,tmp,res);
        if(root->right) 
           dfs(root->right,tmp,res);  
    }
};
发布了48 篇原创文章 · 获赞 29 · 访问量 9797

猜你喜欢

转载自blog.csdn.net/flyconley/article/details/102664162
今日推荐