Simple Python Recursion Code


  • 0
    C
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            res = []
            if root is None:
                return []
            left = self.binaryTreePaths(root.left)
            right = self.binaryTreePaths(root.right)
            if len(left) >= 1:
                res.extend([str(root.val) + "->" + path for path in left])
            if len(right) >= 1:
                res.extend([str(root.val) + "->" + path for path in right])
            if len(left) < 1 and len(right) < 1:
                return([str(root.val)])
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.