---
# System prepended metadata

title: 257. Binary Tree Paths
tags: [C++, LeetCode-Easy]

---

# 257. Binary Tree Paths
Difficulty: Easy

## Solution

```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-11-10
**/
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;

struct TestCasesStruct {};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode() : val(0), left(nullptr), right(nullptr) {}
  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  TreeNode(int x, TreeNode *left, TreeNode *right)
      : val(x), left(left), right(right) {}
};

class Solution {
 public:
  vector<string> binaryTreePaths(TreeNode *root) {
    vector<string> output;

    preorderTraversal(root, "", output);

    return output;
  }

 private:
  void preorderTraversal(TreeNode *node, std::string current_str,
                         vector<string> &output) {
    if (node == nullptr) {
      return;
    }

    if (!current_str.empty()) {
      current_str += "->";
    }
    current_str += std::to_string(node->val);

    if (node->left == nullptr && node->right == nullptr) {
      output.emplace_back(current_str);
      return;
    }

    preorderTraversal(node->left, current_str, output);
    preorderTraversal(node->right, current_str, output);
  }
};

int main(int argc, char *argv[]) { return EXIT_SUCCESS; }

```

## Result
Success
Details 
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Paths.
Memory Usage: 13.5 MB, less than 11.46% of C++ online submissions for Binary Tree Paths.

###### tags: `LeetCode-Easy` `C++`