Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:
Input:

Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3

Solution in python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        alist = []
        def helper(root, temp):
            if root == None:
                return 
            elif (root.left == None) and (root.right == None):
                temp += "->" + str(root.val)
                alist.append(temp)
                return 
            else:
                helper(root.left, temp+"->" + str(root.val))
                helper(root.right, temp+"->" + str(root.val))   
        helper(root, "")
        for i in range(len(alist)):
            alist[i] = (alist[i])[2:]
        return alist
最后修改日期: 2021年1月23日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。