카테고리 없음

NeetCode 22번 알고리즘 Tree Maze

코테챌린져 2024. 7. 20. 17:57

Algorithm

Q: Determine if a path exists from the root of the tree to a leaf node. It may not contain any zeroes.

 

Code

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

def leafPath(root, path):
    if not root or root.val == 0:
        return False
    path.append(root.val)

    if not root.left and not root.right:
        return True
    if leafPath(root.left, path):
        return True
    if leafPath(root.right, path):
        return True
    path.pop()
    return False