3ms c++ recursive solution


  • 0
    J
    vector<string> binaryTreePaths(TreeNode* root)
    	{
    		vector<string> result;
    
    		// sanity check, this is not base condition
    		if (!root)
    		{
    			return result;
    		}
    
    		//
    		// base condition
    		//
    		if (root->left == NULL && root->right == NULL)
    		{
    			result.push_back(to_string(root->val));
    			return result;
    		}
    		
    		//
    		// n -> n+1
    		//
    		vector<string> res_left;
    		if (root->left != NULL)
    		{
    			res_left = binaryTreePaths(root->left);
    		}
    		for (size_t i = 0; i < res_left.size(); i++)
    		{
    			result.push_back(to_string(root->val) + "->" + res_left[i]);
    		}
    
    		vector<string> res_right;
    		if (root->right != NULL)
    		{
    			 res_right = binaryTreePaths(root->right);
    		}
    		for (size_t i = 0; i < res_right.size(); i++)
    		{
    			result.push_back(to_string(root->val) + "->" + res_right[i]);
    		}
    		return result;
    	}
    

Log in to reply
 

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