본문 바로가기
알고리즘/leetcode

1372. Longest ZigZag Path in a Binary Tree - python

by 1.5볼트 2023. 4. 22.
728x90

https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/description/

 

Longest ZigZag Path in a Binary Tree - LeetCode

Can you solve this real interview question? Longest ZigZag Path in a Binary Tree - You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose any node in the binary tree and a direction (right or left). * If the

leetcode.com

지그재그
간단하게 위에서 왼쪽으로 내려갔는지 오른쪽으로 내려갔는지만 확인하면 된다
왼쪽으로 내려왔으면 다음번에 오른쪽으로 가야 1을 더해주고 같은 방향으로 내려가면 지그재그가 아니니까 1을 더해주지 않고 1부터 시작함 그런 식으로 왼쪽으론 오른쪽일 때 오른쪽이면 왼쪽으로 방향만 받아서 계산해 주면 된다 그 주에서 가장 큰 값이니까 전역변수로 최댓값 찾기

 

# 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:
        global m
        m=0
        def f(root,h,n):
            global m
            if not root:
                return  
            if n>m:m=n
            if h==1:
                f(root.left,1,1)
                f(root.right,0,n+1)
            elif h==0:
                f(root.left,1,n+1)
                f(root.right,0,1)
        f(root,0,0)
        return m

 

 

 

'알고리즘 > leetcode' 카테고리의 다른 글

184. Department Highest Salary  (0) 2023.04.28
258. Add Digits  (0) 2023.04.26
946. Validate Stack Sequences - python  (0) 2023.04.15
20. Valid Parentheses - python  (0) 2023.04.11
1020. Number of Enclaves - python  (0) 2023.04.07

댓글