My 8s c++ solve.


  • 2
    G
    #include <algorithm>
    #include <iostream>
    #include <vector>
    #include <string>
    #include <sstream>
    using namespace std;
    
    class Solution {
    	vector<string> result;
    	void printTree(TreeNode* root, string path="")
    	{
    		if (root == NULL) return;
    		stringstream ss;
    		ss << root->val;
    		string n;
    		ss >> n;
    		path += n;
    		if (root->left == NULL && root->right ==NULL) {
    			result.push_back(path);
    		}
    		path += "->";
    		printTree(root->left, path);
    		printTree(root->right, path);
    	}
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
    		printTree(root);
    		return result;   
        }
    };

  • 0
    Q

    Instead of using the stringstream, you could use a simple to_string function to convert the integral root->value to string like:

              path += to_string(root->val)
    

    Just a suggestion to make the code a little more concise.


Log in to reply
 

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