Skip to content

Latest commit

 

History

History
39 lines (29 loc) · 898 Bytes

257.-binary-tree-paths.md

File metadata and controls

39 lines (29 loc) · 898 Bytes

257. Binary Tree Paths

{% tabs %} {% tab title="Python-DFS-recursive" %}

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        
        res = []
        self.dfs(root, [], res)
        return res
        
    
    def dfs(self, root, path, res):
        if not root:
            return 
        
        if not root.left and not root.right:
            res.append("".join(path[:] + [str(root.val)]))

            
        path.append(str(root.val))
        print(path)
        if root.left:
            self.dfs(root.left,path + ["->"], res)
            
        if root.right:
            self.dfs(root.right, path+ ["->"], res)

{% endtab %} {% endtabs %}