PU Binary Tree Paths

Jan 01, 1970

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

For example, given the following binary tree:

   1
 /   
2     3
 
  5

All root-to-leaf paths are:

  • ["1->2->5", "1->3"]

Python Solution:

# 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]
        """
        if not root: return []
        path = []
        res = []
        def postorder(root, path, res):
            path.append(str(root.val))
            if not root.left and not root.right:
                res.append('->'.join(path))
                path.pop()
                return
            if root.left:
                postorder(root.left, path, res)
            if root.right:
                postorder(root.right, path, res)
            path.pop()
        postorder(root, path, res)
        return res

Summary:

  • nothing to say.

LeetCode: 257. Binary Tree Paths