leetcode257 Binary Tree Paths

정은경·2022년 6월 26일
0

알고리즘

목록 보기
106/125

1. 문제

2. 나의 풀이

# 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 getPaths(self, node):
        if node is None:
            return []
        
        if node and (node.left is None and node.right is None):
            return [str(node.val)]
        
        if node.left or node.right:
            nodeValStr = str(node.val)
            return [nodeValStr+"->"+x for x in self.getPaths(node.left)] + [nodeValStr+"->"+x for x in self.getPaths(node.right)]
        
        
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        return self.getPaths(root)

Reference

profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글