LeetCode:257. Binary Tree Paths - Python

257. 二叉树的所有路径

问题描述:

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:
在这里插入图片描述
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

问题分析:

这类题目,和求一个二叉树的所有从根节点到叶子节点的路径和的,是一个类型。具体解法,深度优先搜索

(1)深度优先搜索,递归实现。

(2)确定递归出口,就是一个节点的左右子节点都为空。否则就继续递归。

(3)没到叶子节点,就把这个路径保存一下。

Python3实现:

class TreeNode():  # 定义一个二叉树结构
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def binaryTreePathSum(self, root):

        def dfs(root, path):
            if root:
                path += str(root.val)  # 添加一个节点
                if not root.left and not root.right:  # 如果是叶子节点,输出
                    res.append(path)
                else:
                    path += '->'
                    dfs(root.left, path)  # 左递归
                    dfs(root.right, path)  # 右递归

        res = []  # 用于记录所有路径
        dfs(root, '')
        return res


if __name__ == '__main__':
    solu = Solution()
    tree = TreeNode(1)
    tree2 = TreeNode(2)
    tree3 = TreeNode(3)
    tree4 = TreeNode(5)
    tree.left = tree2
    tree.right = tree3
    tree2.right = tree4
    print(solu.binaryTreePathSum(tree))

如果题目换成,求到所有叶子节点的那?

# @Time   :2019/01/31
# @Author :LiuYinxing
# 深度优先搜索



class TreeNode():  # 定义一个二叉树结构
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def binaryTreePathSum(self, root):

        def dfs(root, paths):
            if root:
                paths += root.val  # 路径相加
                if not root.left and not root.right:  # 叶子节点,输出
                    res.append(paths)
                else:
                    dfs(root.left, paths)  # 左递归
                    dfs(root.right, paths)  # 右递归

        res = []
        dfs(root, 0)
        return res


if __name__ == '__main__':
    solu = Solution()
    tree = TreeNode(5)
    tree2 = TreeNode(4)
    tree3 = TreeNode(8)
    tree.left = tree2
    tree.right = tree3
    print(solu.binaryTreePathSum(tree))

声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。

题目链接参考链接

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/86720936