# Binary Tree Paths

## DFS

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """       
        self.res = []
        def dfs(root, path):
            if not root.left and not root.right:
                self.res.append(path+str(root.val))           
            if root.left:
            # 第二次複習少加了"path" (path+str(root.val)+"->")
            # 出來會少個root很神奇
                dfs(root.left, path+str(root.val)+"->")
            if root.right:
                dfs(root.right, path+str(root.val)+"->")      
        dfs(root,"")
        return self.res
```

## Stack

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        stack = [(root, "")]
        res = []
        while stack:
            node, strr = stack.pop()
            
            if node:
                if not node.left and not node.right:
                    res.append(strr+str(node.val))                
                if node.left:
                    stack.append((node.left, strr + str(node.val) + "->"))
                if node.right:
                    stack.append((node.right, strr + str(node.val) + "->"))
        return res
```


---

# 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://zcjian.gitbook.io/project/tree/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.
