Accepted 4ms c++ solution.


  • 0
    class Solution {
    public:
        std::vector<std::string> binaryTreePaths(TreeNode* root) {
            std::vector<std::string> res;
            if (!root) {
                return res;
            }
            std::string str = std::to_string(root->val);
            if (!root->left && !root->right) {
                res.push_back(str);
                return res;
            }
            if (root->left) {
                binaryTreePathsHelper(root->left, res, str);
            }
            if (root->right) {
                binaryTreePathsHelper(root->right, res, str);
            }
            return res;
        }
    private:
        void binaryTreePathsHelper(TreeNode *root, std::vector<std::string> &res, std::string str) {
            str += "->" + std::to_string(root->val);
            if (!root->left && !root->right) {
                res.push_back(str);
                return;
            }
            if (root->left) {
                binaryTreePathsHelper(root->left, res, str);
            }
            if (root->right) {
                binaryTreePathsHelper(root->right, res, str);
            }
        }
    };

Log in to reply
 

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