moonlightshadow123
4/10/2017 - 3:32 PM

257-Binary-Tree-Paths https://leetcode.com/problems/binary-tree-paths/

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

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        self.pathRecd = []
        if root == None:
            return self.pathRecd
        self.findPath(root, str(root.val))
        return self.pathRecd
    def findPath(self, root, pathString):
        if root.left == None and root.right == None: 
            self.pathRecd.append(pathString)
        if root.left != None:
            self.findPath(root.left, pathString+'->'+str(root.left.val))
        if root.right != None:
            self.findPath(root.right, pathString+'->'+str(root.right.val))

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"]