A neat && simple C++ solution uses recursion


  • -1
    S
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> ret;
            if(root == nullptr) return ret;
            string str = "";
            str += to_string(root->val);
            if(root->left == nullptr && root->right == nullptr){
                vector<string> strvec;
                strvec.push_back(str);
                return strvec;
            }
            str += "->";
            if(root->right == nullptr && root->left !=nullptr)  swap(root->right,root->left);
            if(root->left == nullptr){
                vector<string> right = binaryTreePaths(root->right);
                for(string &s:right){
                    s = str + s;
                }
                return right;
            }
            vector<string> right = binaryTreePaths(root->right);
            vector<string> left = binaryTreePaths(root->left);
            for(string &s: left) s = str + s;
            for(string &s : right){
                s = str + s;
                left.push_back(s);
            }
            return left;
        }
    };

Log in to reply
 

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