二叉树的所有路径

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)
            binaryTreePths(root->left,res,path+"->");
        if(root->right)
            binaryTreePaths(root->right,res,path+"->");
    }
};
发布了88 篇原创文章 · 获赞 9 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/jwy2014/article/details/103003253