[LintCode 480] 二叉树的所有路径(Python)

来源:互联网 发布:钢琴联系软件 编辑:程序博客网 时间:2024/06/06 14:08

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

样例
给出下面这棵二叉树:

   1 /   \2     3 \  5

所有根到叶子的路径为:

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

思路

递归法。用一个数组来存储路径。然后递归遍历左右子树,把所有路径加进来。递归结束的条件是遇到叶节点,即左右节点都为空,然后把当前路径加入待返回的数组中。

代码

"""Definition of TreeNode:class TreeNode:    def __init__(self, val):        self.val = val        self.left, self.right = None, None"""class Solution:    # @param {TreeNode} root the root of the binary tree    # @return {List[str]} all root-to-leaf paths    def binaryTreePaths(self, root):        # Write your code here        path = ''        res = []        self.TreePathsHelper(root, path, res)        return res    def TreePathsHelper(self, root, path, res):        if root is None:            return        path += str(root.val)        if root.left is not None:            self.TreePathsHelper(root.left, path + '->', res)        if root.right is not None:            self.TreePathsHelper(root.right, path + '->', res)        if root.left is None and root.right is None:            res.append(path)
原创粉丝点击