Accepted 4ms c++ solution


  • 2
    M
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
        vector<string> mypaths;
    public:
        void helper(TreeNode *root, string path){
            if(!root->left && !root->right){
                path=path+to_string(root->val);
                mypaths.push_back(path);
            }
            else if(!root->left && root->right){
                path=path+to_string(root->val)+"->";
                helper(root->right,path);
            }
            else if(root->left && !root->right){
                path=path+to_string(root->val)+"->";
                helper(root->left, path);
            }
            else{
                path=path+to_string(root->val)+"->";
                string path2=path;
                helper(root->left,path);
                helper(root->right,path2);
            }
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            if(root){
                string path;
                helper(root,path);
            }
            return mypaths;
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.