4ms C++ Solution


  • 0
    D
    class Solution {
    public:
        vector <int> path;
        vector <string> ans;
        string makePath() {
            string res;
            for (int i = 0; i < path.size(); i++) {
                res += to_string(path[i]);
                if (i + 1 != path.size()) res += "->";
            }
            return res;
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            traversal(root);
            return ans;
        }
        void traversal(TreeNode * node) {
            if (!node) return;
            path.push_back(node->val); // add to the pass
            
            if (!node->left && !node->right) 
                ans.push_back(makePath());
            
            traversal(node->left);
            traversal(node->right);
            path.pop_back();    // delete from the pass
        }
    };

Log in to reply
 

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