【LeetCode】257. 二叉树的所有路径

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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
#!/usr/bin/python3

# -*- coding: utf-8 -*-

# @Time: 2018/8/14

# @Author: xfLi

#@解题思路:字符串添加路径节点,再将字符串添加到列表中

class TreeNode(object):
    def __init__(self,val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def binaryTreePaths(root):
    """
    :type root: TreeNode
    :rtype: List[str]
    """
    res = []
    path = ''
    if root is None:
        return []
    subTreePath(root, path, res)
    return res

def subTreePath(root, path, res):
    path += str(root.val)
    if root.left is None and root.right is None:
        res.append(path)
    if root.left is not None:
        subTreePath(root.left, path + '->', res)
    if root.right is not None:
        subTreePath(root.right, path + '->', res)

if __name__ == '__main__':
    root = TreeNode(val=1, left=TreeNode(2, left=TreeNode(3), right=TreeNode(4)),
                    right=TreeNode(5, left=TreeNode(6), right=TreeNode(7)))
    result = binaryTreePaths(root)
    print(result)
    
    
    

猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/81672678
今日推荐