Recursive c++ solution


  • 0
    P
    /**
     * 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 {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> v;
            string s;
            if (!root) return v;
            binaryTreePaths(root, s, v);
            return v;
        }
        void binaryTreePaths(TreeNode* r, string s, vector<string>& v) {
            if (!r) return;
            stringstream ss;
            ss << r->val;
            if (!r->left && !r->right) {
                v.push_back(s.empty()?(s+ss.str()):(s+'-'+'>'+ss.str()));
                return;
            }
            binaryTreePaths(r->left, s.empty()?(s+ss.str()):(s+'-'+'>'+ss.str()), v);
            binaryTreePaths(r->right, s.empty()?(s+ss.str()):(s+'-'+'>'+ss.str()), v);
        }
    };

Log in to reply
 

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