二叉樹的所有路徑

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+"->");
    }
};

 

發佈了89 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章