LeetCode/LeetCode75

[LeetCode 75] Medium - 1372. Longest ZigZag Path in a Binary Tree

hyunkookim 2024. 11. 17. 16:17

1372. Longest ZigZag Path in a Binary Tree

 

# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
        res = 0

        def dfs(node, left2right, depth):
            nonlocal res
            
            if node == None: # 끝에 도달
                return
            
            depth += 1 # root 는 depth 0로, 1번째 자식 노드에서 1추가하는 것이..
            res = max(res, depth)
            
            if left2right: # left->right 에서 왔니?
                dfs(node.left, False, depth) # to left
                dfs(node.right, True, 0) # 새롭게 출발, to right 
            else:
                dfs(node.left, False, 0) # 새롭게 출발, to left 
                dfs(node.right, True, depth) # to right


        dfs(root.left, False, 0) # to left, depth=0
        dfs(root.right, True, 0) # to right, depth=0

        return res

 

https://youtu.be/5W7LlybzdD4?si=k0JbiZNRLYcr11k_