# 257. Binary Tree Paths

## problem description

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

**Example:**

```
Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3
```

## algorithm thought

就是将DFS的路线标记出来，最后返回。直接使用DFS做即可

只是这题需要注意一些细节，不然容易过不了一些测试样例

## code

```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root==nullptr)
            return res;
        string path=to_string(root->val);
        if(root->left!=nullptr)
            help(res,root->left,path);
        path=to_string(root->val);
        if(root->right!=nullptr)
            help(res,root->right,path);
        if(root->left==nullptr&&root->right==nullptr){
            res.push_back(path);
        }
        return res;
    }
    void help(vector<string>&res,TreeNode* root,string&path){
        int sz=path.size();
        string number=to_string(root->val);
        path+="->";path+=number;
        if(root->left==nullptr&&root->right==nullptr){
            res.push_back(path);
            path.resize(sz);
            return;
        }
        if(root->left!=nullptr)
            help(res,root->left,path);
        if(root->right!=nullptr)
            help(res,root->right,path);
        path.resize(sz);
    }
};
```

## algorithm analysis

DFS将树遍历一遍，时间复杂度O(n)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kongchengzhuge.gitbook.io/leetcode/257.-binary-tree-paths.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
