My solution using recursion


  • 0
    V
    class Solution {
    private:
        vector<int> store;
        vector<string> result;
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            if( !root )
                return result;
            // push the value into vector
            store.push_back( root->val );
            // end if the node is a leaf
            if( !root->left && !root->right )
            {
                stringstream ss;
                ss << store[ 0 ];
            
                for( int i = 1; i < store.size(); i++ )
                    ss << "->" << store[ i ];
                
                string temp;
                ss >> temp;
                result.push_back( temp );
            }
       
            binaryTreePaths( root->left );
            binaryTreePaths( root->right );
            
            store.pop_back();
        
            return result;
        }
    };

Log in to reply
 

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