美文网首页
Leetcode-257题:Binary Tree Paths

Leetcode-257题:Binary Tree Paths

作者: 八刀一闪 | 来源:发表于2016-10-08 22:15 被阅读27次

    题目

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

    代码

    # 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 visit(self, root, cur_path, pathes):
            cur_path.append(root.val)
            if root.left==None and root.right==None:
                pathes.append('->'.join([str(n) for n in cur_path]))
            else:
                if root.left != None:
                    self.visit(root.left, cur_path, pathes)
                if root.right != None:
                    self.visit(root.right, cur_path, pathes)
            cur_path.pop()
    
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if root == None:
                return []
            res = []
            self.visit(root,[],res)
            return res
    

    相关文章

      网友评论

          本文标题:Leetcode-257题:Binary Tree Paths

          本文链接:https://www.haomeiwen.com/subject/rrcpyttx.html