# LC 257. Binary Tree Paths ### [Problem link](https://leetcode.com/problems/binary-tree-paths/) ###### tags: `leedcode` `easy` `c++` `Binary Tree` Given the <code>root</code> of a binary tree, return all root-to-leaf paths in **any order** . A **leaf** is a node with no children. **Example 1:** <img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" style="width: 207px; height: 293px;" /> ``` Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"] ``` **Example 2:** ``` Input: root = [1] Output: ["1"] ``` **Constraints:** - The number of nodes in the tree is in the range <code>[1, 100]</code>. - <code>-100 <= Node.val <= 100</code> ## Solution 1 #### C++ ```cpp= class Solution { public: vector<string> res; void traversal(TreeNode *node, string path) { path += to_string(node->val); if (node->left == nullptr && node->right == nullptr) { res.push_back(path); } if (node->left != nullptr) { traversal(node->left, path + "->"); } if (node->right != nullptr) { traversal(node->right, path+ "->"); } } vector<string> binaryTreePaths(TreeNode* root) { string path; if (root == nullptr) { return res; } traversal(root, path); return res; } }; ``` >### Complexity >| | Time Complexity | Space Complexity | >| ----------- | --------------- | ---------------- | >| Solution 1 | O(n) | O(1) | ## Note x
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up