Untitled

mail@pastecode.io avatar
unknown
python
2 months ago
1.0 kB
2
Indexable
Never
# 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 amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        self.infected = None
        root.parent = None
        def set_parent(node):
            if node is None:
                return
            if node.val == start:
                self.infected = node
            if node.left is not None:
                node.left.parent = node
                set_parent(node.left)
            if node.right is not None:
                node.right.parent = node
                set_parent(node.right)
        set_parent(root)
        visited = set()
        def infect(node):
            if node is None or node.val in visited:
                return 0
            visited.add(node.val)
            return max(infect(node.left),infect(node.right),infect(node.parent)) + 1
        
        return infect(self.infected) - 1

Leave a Comment